【问题标题】:MongoDB - Select all documents by the count of an array fieldMongoDB - 通过数组字段的计数选择所有文档
【发布时间】:2017-05-11 07:17:05
【问题描述】:

在我当前的项目中,我有这样的结构:

"squad": {
    "members": [
        {
            "name": "xyz",
            "empty": true
        },
        {
            "name": "xyz",
            "empty": true
        },
        {
            "name": "xyz",
            "empty": true
        }
    ]
}

现在我想用 mongodb 查询每个小队,其中至少有 3 个空的成员槽。我用谷歌搜索,只找到聚合和 $size,这似乎只选择一个数组计数而不是每个字段。
知道怎么做吗?

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    你可以试试这个查询:

    db.getCollection('collectionName').aggregate([
      {$unwind:"$squad.members"},
      {$group:{_id:"$_id",count:{$sum:{$cond: [{$eq: ['$squad.members.empty', true]}, 1, 0]}}}},
      {$match: {count: {$gte: 3}}}
    ])
    

    在此查询中应用条件总和,然后检查计数是否大于或等于3

    【讨论】:

      【解决方案2】:

      它将返回所有文档将空槽大于 3

      db.squad.aggregate([
        {$unwind:"$squad.members"},
        {$match:{"squad.members.empty": true}},
        {$group:{_id:"$_id",count:{$sum:1}}},
        {$match: {count: {$gt: 3}}}
      ])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-01
        • 2021-07-15
        • 1970-01-01
        • 2017-03-06
        • 1970-01-01
        • 2021-07-24
        • 1970-01-01
        相关资源
        最近更新 更多