(Sorry if it's a trivial question.)
I have documents that looks like this (Python syntax):
{
'_id': SomeObjectId,
'features': [
{'id': 'featureX' , 'value': 6},
{'id': 'featureY', 'value': 45}
]
}
With this structure it's easy to find all documents that contains 'featureX' in the list of features. But I'm also interested in retrieving the value associated in the sub-document.
I think in Python if I get the document with a query like this: db.articles.find({'features.id': 'featureX'})
then I would need to iterate over the array 'features' to find out the correct 'value'.
Is there an other kind of query that can give me the interesting value (in this case I don't need to retrieve the full document, only the part with {'id': 'featureX', 'value': 6}, which won't be at a predictable index value in the array.
PS: I think I will design the document differently, but I'm still interested to know if the resquest above is feasible.
Here is the new structure:
{
'_id': SomeObjectId,
'features': {
'featureX': { 'someproperty':'aaa', 'value':6 },
'featureY': {'someproperty' :'bbb', 'value':45}
}
}
Is there any issue about this desgin ? In my case 'featureX', 'featureY' are unique so using them as dictionnary keys is not a problem.
Edit: I need to clarify that I will need to update atomically say 'featureX' and 'featureY' in a document and MongoDB does not support transactions. Also the second design, while not allowing to retrieve a subdocument, should makes it easy to get quickly the desired information in the client code, assuming that I can query for sub-documents having a certain key.
I think that this query should do the job:
result = db.articles.find_one({ 'features.featureX': {'$exists': True} } )
interesting_value = result['features']['featureX']['value']