简体   繁体   中英

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 ?

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'}}
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM