Given the example doc below:
{
"_id" : "2",
"objects" : [{
"_id" : "1",
"name" : "embedded "
},{
"_id" : "2",
"name" : "embedded "
},{
"_id" : "3",
"name" : "embedded "
}],
"name" : "gloss2"
}
Is it possible to return only one subdocument? That way I don't have to select the whole parent object, get the list, and loop through the list to get the object in question.
{
"_id" : "2",
"name" : "embedded"
}
Is it possible to return only one subdocument?
Yes, but not the way you want. If you do the following, you will only get back the first element of the array:
coll.find({_id:'2'}, { 'objects.0': 1})
However, what you really want is something that looks like the following:
coll.find({_id:'2', 'objects._id': '3'}, { 'objects.$' : 1})
Of course, that does not actually work in MongoDB.
Looking at your other question, this is one of the reasons to use the "embedded object" instead of the "array of objects". With "embedded object" you could do the following:
coll.find({_id:'2'}, {'objects.3': 1}) // where 3 is the id of the third object
This lets you pick just the "embedded objects" you need.
That way I don't have to select the whole parent object...
The thing with MongoDB is that the parent document is always fetched. Queries return top-level documents. This is baked into the whole architecture. Even if you request just a slice of the document the server still has to load the entire document into memory before serving you the requested piece.
The only way around this may be the new Aggregation Framework, but that is not yet in the stable branch.
You can do it with mongo > 2.2 version.
db.collection.find({'objects._id':1},{'objects.$': true})
But you just get the first match element http://docs.mongodb.org/manual/reference/projection/positional/
You can return one subdocument, but you can't return one element from an array. Sorry.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With