【问题标题】:MongoDB multiple counts, single document, arraysMongoDB 多次计数、单个文档、数组
【发布时间】:2019-10-04 07:27:24
【问题描述】:

我一直在 stackoverflow 上搜索,但找不到我正在寻找的确切内容,希望有人能提供帮助。我想根据该文档的数组提交单个查询,为单个文档返回多个计数。

我的数据:

db.myCollection.InsertOne({
  "_id": "1",
  "age": 30,
  "items": [
    {
      "id": "1",
      "isSuccessful": true,
      "name": null
    },{
      "id": "2",
      "isSuccessful": true,
      "name": null
    },{
      "id": "3",
      "isSuccessful": true,
      "name": "Bob"
    },{
      "id": "4",
      "isSuccessful": null,
      "name": "Todd"
    }
  ]
});

db.myCollection.InsertOne({
  "_id": "2",
  "age": 22,
  "items": [
    {
      "id": "6",
      "isSuccessful": true,
      "name": "Jeff"
    }
  ]
});

我需要返回的是文档以及与所述文档的 items 数组关联的计数。在此示例中,文档 _id = "1":

{
  "_id": "1", 
  "age": 30,
  {
    "totalIsSuccessful" : 2,
    "totalNotIsSuccessful": 1,
    "totalSuccessfulNull": 1,
    "totalNameNull": 2
  }
}

我发现我可以使用下面类似的方法在 4 个查询中得到这个,但我真的希望它是一个查询。

db.test1.aggregate([
  { $match : { _id : "1" } },
  { "$project": {
    "total": {
      "$size": {
        "$filter": {
          "input": "$items",
          "cond": { "$eq": [ "$$this.isSuccessful", true ] }
        }
      }
    }
  }}
])

提前致谢。

【问题讨论】:

标签: mongodb mongodb-query


【解决方案1】:

我假设您的预期结果是无效的,因为您在另一个对象的中间有一个对象文字,而且您有 totalIsSuccessful 用于 id:12,它们似乎应该是 3。话虽如此......

你可以通过$unwind得到类似的输出,然后用$sum$cond分组:

db.collection.aggregate([
  { $match: { _id: "1" } },
  { $unwind: "$items" },
  { $group: { 
    _id: "_id",
    age: { $first: "$age" },
    totalIsSuccessful: { $sum: { $cond: [{ "$eq": [ "$items.isSuccessful", true ] }, 1, 0 ] } },
    totalNotIsSuccessful: { $sum: { $cond: [{ "$ne": [ "$items.isSuccessful", true ] }, 1, 0 ] } },
    totalSuccessfulNull: { $sum: { $cond: [{ "$eq": [ "$items.isSuccessful", null ] }, 1, 0 ] } },
    totalNameNull: { $sum: { $cond: [ { "$eq": [ "$items.name", null ]}, 1, 0] } } }
  }
])

输出是这样的:

[
  {
    "_id": "_id",
    "age": 30,
    "totalIsSuccessful": 3,
    "totalNameNull": 2,
    "totalNotIsSuccessful": 1,
    "totalSuccessfulNull": 1
  }
]

你可以see it working here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 2021-06-26
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 1970-01-01
    相关资源
    最近更新 更多