【问题标题】:MongoDB find subdocument idsMongoDB查找子文档ID
【发布时间】:2012-11-26 03:52:28
【问题描述】:

我的架构设置是这样的:

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

我的要求是,给定_id,我需要找到所有将is_user 设置为true 的朋友ID (fid)

我尝试了以下方法:

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

似乎将整个集合中的结果返回给我,但我想要它作为 ID。所以我尝试了这个:

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

但这什么也没给我。另外,我只需要返回 fid 。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: mongodb mongodb-java mongodb-query


    【解决方案1】:

    在这种情况下,您需要的不仅仅是数组中的第一个匹配元素,您必须使用aggregation framework 而不是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'}}
    ]);
    

    【讨论】:

    • 谢谢 JohnnyHK ..(和 Chris :))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 2021-07-25
    • 2021-07-05
    • 2016-08-25
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多