nobillygreen
nobillygreen

Reputation: 1588

Find Subdocument by Id based on value in parent

Given that I have a document of the following structure:

{
    selectedId: ObjectId("57b5fb2d7b41dde99009bc75"),
    children: [
        {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 10},
        {_id: ObjectId("57b5fb2d7b41dde99009bc75"), val: 20},
    ]
}

where the parent value "selectedId" always references one of the children Id, how do I just get the child subdocument where _id = selectedId?

I attempted:

parentModel.findOne({'selectedId': 'this.children._id'})

however, as I now know, the second string is taken as a literal. So how do I reference the parent's field in the query?

Edit: obviously, this could be done with two queries, getting the parent's "selectedId" value and then querying again. However, I want to do this in a single query.

Upvotes: 0

Views: 265

Answers (1)

chridam
chridam

Reputation: 103365

You could use the aggregation framework, in particular leverage the $arrayElemAt and $filter operators to return the child subdocument. The following example shows this:

parentModel.aggregate([
    {
        "$project": {
            "children": {
                "$arrayElemAt": [
                    {
                        "$filter": {
                            "input": "$children",
                            "as": "item",
                            "cond": {
                                "$eq": ["$$item._id", "$selectedId"]
                            }
                        }
                    }, 0
                ]
            }
        }
    }
]).exec(callback);

Upvotes: 1

Related Questions