Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find subdocument by id inside a array field of nested object

If I have a document like this:

{
   "_id": ObjectId("54e6774a73a7edfefdb9e2bc"),
   "information":"",
   "__v":0,
   "goalieRoster":{
      "locked":[

      ],
      "approved":[
         {
            "_id": ObjectId("548d49bad972605bf2d1f55a"), // find by this
         }
      ],
      "signedUp":[
         {
            "_id": ObjectId("548d49bad972605bf2d1f55a"),
         }
      ],
      "maxSize":2
   },
   "skaterRoster":{
      "locked":[

      ],
      "approved":[

      ],
      "signedUp":[

      ],
      "maxSize":26
   },
   "date":{
      "updated":"2015-02-20T02:56:42.258Z",
      "skate":""
   }
}

How would I grab the whole subdocument inside approved by the subdocument's id? I think I am close, as the following query almost does what I want.

db.roster.find(
        {
            "goalieRoster.approved._id": ObjectId("548d54e9576ddacc20f3a88e")
        },
        {
            "goalieRoster.approved": 1
        }
);

It returns the parent document and the than the matching subdocument inside approved array nested inside goalieRoster like so

{
    "_id" : ObjectId("54e6774a73a7edfefdb9e2bc"),
    "goalieRoster" : {
        "approved" : [
            {
                "_id" : ObjectId("548d54e9576ddacc20f3a88e"),
            }
        ]
    }
}

The problem is all i want is the subdocument inside approved. Also, is it possible to drop the goalieRoster to just approved and have it look inside both the approved array in goalieRoster and skaterRoster?

Edit: The result I was looking for is this

{
    "_id" : ObjectId("548d54e9576ddacc20f3a88e"),
}
like image 667
cbalos Avatar asked Feb 23 '15 00:02

cbalos


1 Answers

What you want is projection with the $ operator.

db.test.find({"goalieRoster.approved._id": ObjectId("548d49bad972605bf2d1f55a")},
    {"goalieRoster.approved.$": true}
)

Result

{
    "_id" : "54e6774a73a7edfefdb9e2bc", 
    "goalieRoster" : { "approved" : [ { "_id" : "548d54e9576ddacc20f3a88e" } ] }
}
like image 112
styvane Avatar answered Oct 02 '22 14:10

styvane