MongoDB找到子文档ID

sha*_*ath 1 mongodb mongodb-java mongodb-query

我有这样的架构设置:

{
 _id:1234,
 friends: [
           {
             "fid":1235
             "is_user":true
           },
           {
             "fid":1236
             "is_user":true
           },
           {
             "fid":1235
             "is_user":false
           }
          ]
 }
Run Code Online (Sandbox Code Playgroud)

我的要求是,给定一个_id,我需要找到所有的朋友IDS (fid)谁已is_user设置为true.

我尝试了以下方法:

db.users.find({ friends: { $elemMatch : { is_app_user: true}}});
Run Code Online (Sandbox Code Playgroud)

似乎在整个系列中给我回复结果,但我想要它用于ID.所以我试过这个:

db.users.find({_id:1234},{friends: { $elemMatch : { is_app_user: true}}});
Run Code Online (Sandbox Code Playgroud)

但这没有给我什么.而且,我所需要的只是fid.有人可以帮我解决这个问题吗?

Joh*_*yHK 8

在这种情况下,您需要的不仅仅是数组中的第一个匹配元素,您必须使用聚合框架而不是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'}}
]);
Run Code Online (Sandbox Code Playgroud)