sharath
sharath

Reputation: 3616

MongoDB find subdocument ids

I have my schema setup this way:

{
 _id:1234,
 friends: [
           {
             "fid":1235
             "is_user":true
           },
           {
             "fid":1236
             "is_user":true
           },
           {
             "fid":1235
             "is_user":false
           }
          ]
 }

My requirement is that, given a _id, I need to find all the friend ids (fid) who have is_user set to true.

I tried the following :

db.users.find({ friends: { $elemMatch : { is_app_user: true}}});

seems to give me back results in the whole collection, but I want it for an ID. so I tried this:

db.users.find({_id:1234},{friends: { $elemMatch : { is_app_user: true}}});

but that gave me nothing. Also, all I need back is the fid . Can somebody help me out with this ?

Upvotes: 1

Views: 1493

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

In a case like this where you want more than just the first matching element from the array, you have to use the aggregation framework instead of a find.

db.users.aggregate([
    // Find the matching document
    { $match: { _id: 1234 }},
    // Duplicate the document for each element of friends
    { $unwind: '$friends' },
    // Filter the documents to just those where friends.is_user = true
    { $match: { 'friends.is_user': true }},
    // Only include fid in the results
    { $project: { _id: 0, fid: '$friends.fid'}}
]);

Upvotes: 8

Related Questions