Mongodb select field to return inline document to array

For an example below:

{ "_id" : "2", "objects" : [{ "_id" : "1", "name" : "embedded " },{ "_id" : "2", "name" : "embedded " },{ "_id" : "3", "name" : "embedded " }], "name" : "gloss2" } 

Can only one subdocument be returned? That way, I don’t have to select the whole parent object, get the list and scroll through the list to get the object in question.

 { "_id" : "2", "name" : "embedded" } 
+7
source share
5 answers

Can only one subdocument be returned?

Yes, but not the way you want. If you do the following, you will get only the first element of the array:

 coll.find({_id:'2'}, { 'objects.0': 1}) 

However, what you really want is what looks like this:

 coll.find({_id:'2', 'objects._id': '3'}, { 'objects.$' : 1}) 

Of course, this does not work in MongoDB.

Considering your other question , this is one of the reasons for using an "embedded object" instead of an "array of objects". Using the "inline object" you can do the following:

 coll.find({_id:'2'}, {'objects.3': 1}) // where 3 is the id of the third object 

This allows you to select only the "built-in objects" that you need.

This way, I do not need to select the entire parent ...

The thing with MongoDB is that the parent document is always checked out. Queries return top-level documents. It is baked throughout the architecture. Even if you request only a fragment of a document, the server should still load the entire document into memory before serving you the requested fragment.

The only way around this may be a new Aggregation Structure , but it is not yet in a stable branch.

+14
source

You can return one subdocument, but you cannot return one element from an array. Unfortunately.

+2
source

You can do this with mongo version> 2.2.

db.collection.find ({'objects._id': 1}, {'objects. $': true})

But you just get the first matching element http://docs.mongodb.org/manual/reference/projection/positional/

+2
source

The latest version of mongodb (now 2.6) has a $elemMatch projection that helps us in this case. If this helps someone, there are several examples on this page: http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/#proj._S_elemMatch

0
source

Mongodb 3.2 introduces $ elemMatch so that you can get only one first matching document from an array of documents.

 db.sample.find({_id:"2"},{objects:{$elemMatch:{_id:"2"}}}) 
0
source

All Articles