paynestrike
paynestrike

Reputation: 4658

How to query parent based on subdocument's _id?

consider the following records:

user record

{ 
"_id" : ObjectId("5234ccb7687ea597eabee677"),
"class" : [
         { "_id" :  ObjectId("5234ccb7687ea597eabee671", "num" : 10, "color" : "blue" },
         { "_id" :  ObjectId("5234ccb7687ea597eabee672", "num" : 100, "color" : "blue" }
       ]
}

this user has two class sub records, now I need a query that finds all users that have class property where "class._id" has a value of at least one users "class._id"

here is a more detail example:

suppose there is four user:

A:{_id:432645624232345,class:[{_id:123,name:'foo'}]}
B:{_id:432645624232555,class:[{_id:555,name:'foo'},{_id:123,name:'foo'}]}
C:{_id:432645344232345,class:[{_id:555,name:'foo'},{_id:111,name:'www'}]}
D:{_id:432644444232345,class:[{_id:222,name:'sss'},{_id:555,name:'www'},{_id:123,name:'foo'}]}

now if B login , I need to query all the user whose class subdocument contains at least one document which's _id==555 or _id==123 (555 and 123 come from B user), in this case the query result should be:

A:{_id:432645624232345,class:[{_id:123,name:'foo'}]}  // match _id=123
B:{_id:432645624232555,class:[{_id:555,name:'foo'},{_id:123,name:'foo'}]} //match _id=123 and _id=555
C:{_id:432645344232345,class:[{_id:555,name:'foo'},{_id:111,name:'www'}]}  //match _id=555
D:{_id:432644444232345,class:[{_id:222,name:'sss'},{_id:555,name:'www'},{_id:123,name:'foo'}]}  ///match _id=123 and _id=555

which is all the user.

so far i get this:

{"class._id" : { $in : ["5234ccb7687ea597eabee671", "5234ccb7687ea597eabee672"] } }

but when different user login the class._id query condition is different. So is there any operator to do this

{"class._id" : { $in : req.user.class } }

hope I made myself clear.

Upvotes: 0

Views: 113

Answers (2)

Schiller
Schiller

Reputation: 98

In order to achieve what you want, first you must isolate the class _ids in an array, and then use it in the query argument.

var classIds = [];
var i = 0;
while (i < req.user.class.length) {
    classIds.push(req.user.class[i]._id);
    i++;
}

After that you can use classIds array in the query:

{"class._id" : { $in : classIds } }

Upvotes: 0

user2941651
user2941651

Reputation:

The following query condition would give you all the users that have at least one class with id equal to any of the elements in the given array:

{"class._id" : { $in : ["5234ccb7687ea597eabee671", "5234ccb7687ea597eabee672"] } }

In the array for the $in clause you may provide any id's you needed , comma separated.

In addition, if you needed such, the below query condition should check for existence of nested document within "class" property that has a property "_id" :

{ "class._id" : { $exists : true } }

Both conditions should work no matter if "class._id" is a single-valued property or an array (mongo supports that).

Upvotes: 0

Related Questions