Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb select field to return embedded document in array

Tags:

mongodb

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"
}
like image 876
Fredrik L Avatar asked Feb 08 '12 21:02

Fredrik L


3 Answers

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.

like image 151
Gates VP Avatar answered Nov 14 '22 07:11

Gates VP


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/

like image 3
kop Avatar answered Nov 14 '22 07:11

kop


You can return one subdocument, but you can't return one element from an array. Sorry.

like image 2
Eve Freeman Avatar answered Nov 14 '22 07:11

Eve Freeman