mongoDB多重计数查询

时间:2018-06-29 10:32:06

标签: mongodb

我的MongoDB中的文档结构如下:

{ "_id": ObjectId("59b799e462f0b9402dbcd69e"), "project": "ABC", "locked": true }

{ "_id": ObjectId("59b799e462f0b9402dbcd69f"), "project": "DEF", "locked": false }

{ "_id": ObjectId("59b799e462f0b9402dbcd70a"), "project": "XYZ", "locked": true }

{ "_id": ObjectId("59b799e462f0b9402dbcd70b"), "project": "ABC", "locked": true }

{ "_id": ObjectId("59b799e462f0b9402dbcd70c"), "project": "XYZ", "locked": false }

我想找出按项目字段分组的已锁定和未锁定项目的数量,这应该给我这样的信息:

[
  {
     project: "ABC",
     lockedCount: 2,
     unlockedCount: 0,
     totalCount: 2
  },
  {
     project: "DEF",
     lockedCount: 0,
     unlockedCount: 1,
     totalCount: 1
  },
  {
     project: "XYZ",
     lockedCount: 1,
     unlockedCount: 1,
     totalCount: 2
  }
]

是否可以仅使用1个查询?

1 个答案:

答案 0 :(得分:0)

您可以使用Aggregate操作来做到这一点。

db.yourCollectionName.aggregate(
[{
    $group : {
        _id : "$project",
        "lockedCount" : {$sum : {
             $cond: { if: "$locked", then: 1, else: 0 }
           }},
           "unlockedCount" : {$sum : {
             $cond: { if: "$locked", then: 0, else: 1 }
           }},
         "totalCount" : {$sum : 1}
        }
    }]
)

输出:

/* 1 */
{
    "_id" : "XYZ",
    "lockedCount" : 1.0,
    "unlockedCount" : 1.0,
    "totalCount" : 2.0
}

/* 2 */
{
    "_id" : "DEF",
    "lockedCount" : 0.0,
    "unlockedCount" : 1.0,
    "totalCount" : 1.0
}

/* 3 */
{
    "_id" : "ABC",
    "lockedCount" : 2.0,
    "unlockedCount" : 0.0,
    "totalCount" : 2.0
}

已更新

如果您想用_id重命名project,则可以在$project操作结束时使用$group,如下所示:

db.yourCollectionName.aggregate(
    [{
        $group : {
            _id : "$project",
            "lockedCount" : {$sum : {
                 $cond: { if: "$locked", then: 1, else: 0 }
               }},
               "unlockedCount" : {$sum : {
                 $cond: { if: "$locked", then: 0, else: 1 }
               }},
             "totalCount" : {$sum : 1}
            }
        },
        {
        $project : {
            _id : 0,
            project : "$_id",
            lockedCount : "$lockedCount",
            unLockedCount : "$unlockedCount",
            totalCount : "$totalCount"
            }
        }]
    )

输出:

/* 1 */
{
    "project" : "XYZ",
    "lockedCount" : 1.0,
    "unLockedCount" : 1.0,
    "totalCount" : 2.0
}

/* 2 */
{
    "project" : "DEF",
    "lockedCount" : 0.0,
    "unLockedCount" : 1.0,
    "totalCount" : 1.0
}

/* 3 */
{
    "project" : "ABC",
    "lockedCount" : 2.0,
    "unLockedCount" : 0.0,
    "totalCount" : 2.0
}