Search code examples
mongodbsubdocument

Mondodb what is the best way to retrieve a subdocument by Id, If I know parent id and sub id


Now I'm doing it like so

Client.findOne({_id: client_id}, function (err, client) {

        if(err){ return next() }

        var phone = client.phones.filter(function (phone) {
             return phone._id === phone_id;
        }).pop();

        res.status(200).send(phone);
});

,but not sure if that the right way of doing it. My schema is like this

{
    "_id" : ObjectId("560b05b6fd9d267f60b7bb28"),
    "email" : "[email protected]",
    "__v" : 1,
    "phones" : [
        {
            "_id" : ObjectId("561a22cbe6ebf6d62965b4bc"),
            "phone" : "1234"
        }
    ]
}

So I would like to get phone 1234 by 560b05b6fd9d267f60b7bb28 and 561a22cbe6ebf6d62965b4bc


Solution

  • A subdocument can't have an _id, at least not with the same semantics. A document's _id is always indexed and has to be unique and has some other implications. The _id field in the phones array of your documents is a normal field as phone.

    So you can access it the usual way. In shell terms:

    var doc = db.phones.findOne(
      // query part
      {
        "_id": knownIdOfDocument,
        "phones": $elemMatch:{"_id": knownIdOfSubdocument}
      },
      // projection
      { "phones.$":1 }
    )
    var phone = doc['phones'][0]; // Iirc, my JS is a bit rusty.