类似于SELECT COUNT GROUP BY的MongoDB查询

jdzmm42g  于 2022-11-22  发布在  Go
关注(0)|答案(2)|浏览(129)

我的MongoDB数据库有一个'interview'集合,它的文档结构类似于:

{
    "_id" : ObjectId("632b97b0f2bd3f64bbc30ec8"),
    "agency" : "AG1",
    "year" : "2022",
    "month" : "9",
    "residents" : [
        {
            "sequential" : 1,
            "name" : "Resident 1",
            "statusResident" : "pending",
        },
        {
            "sequential" : 2,
            "name" : "Resident 2",
            "statusResident" : "not analyzed"
        },
        {
            "sequential" : 3,
            "name" : "Resident 3",
            "statusResident" : "not analyzed"
        },
        {
            "sequential" : 4,
            "name" : "Resident 4",
            "statusResident" : "finished"
        }
    ]
}

{
    "_id" : ObjectId("882b99b0f2bd3f64xxc30ec8"),
    "agency" : "AG2",
    "year" : "2022",
    "month" : "9",
    "residents" : [
        {
            "sequential" : 1,
            "name" : "Resident 10",
            "statusResident" : "pending",
        },
        {
            "sequential" : 2,
            "name" : "Resident 20",
            "statusResident" : "not analyzed"
        }
    ]
}

我想创建一个查询,返回类似于SQL SELECT agency, statusResident, COUNT(*) FROM interviews GROUP BY agency, statusResident的内容。
对于上面的这些文档,将返回类似于

AG1     pending        1
AG1     not analyzed   2
AG1     finished       1
AG2     pending        1
AG2     not analyzed   1

我运行了以下查询,但它们没有返回我所需的内容:

db.interviews.aggregate([
                 { $group: { _id: { agency: "$agency", statusResident: "$residents.statusResident", total: { $sum: "$residents.statusResident" } } } },
                 { $sort: { agency: 1 } } 
               

db.interviews.group({
    key:{agency:1, "residents.statusResident":1},
    cond:{year:2022},
    reduce:function(current, result)
       {
         result.total += 1;
       },
         initial:{total:0}
       })

我已经查阅了post“MongoDB SELECT COUNT GROUP BY“和“Select count group by mongodb“以及MongoDB文档,但是没有任何结果。我应该运行什么查询来获得与我想要的结果相似的结果?

vsaztqbk

vsaztqbk1#

试试这个

db.collection.aggregate([
  { $unwind: "$residents" },
  {
    $group: {
      _id: {
        agency: "$agency",
        statusResident: "$residents.statusResident",
        total: { $sum: 1 }
      }
    }
  },
  { $sort: { agency: 1 } }
])

Mongo Playground

z0qdvdin

z0qdvdin2#

您可以尝试以下查询:

  • 第一个$unwind解构数组,也可以按statusResident分组。
  • 然后$group乘以两个值,agencystatusResident
  • 最后一级是$project,以获得更易于读取的输出。
db.collection.aggregate([
  {
    "$unwind": "$residents"
  },
  {
    "$group": {
      "_id": {
        "agency": "$agency",
        "statusResident": "$residents.statusResident"
      },
      "total": {
        "$sum": 1
      }
    }
  },
  {
    "$project": {
      "_id": 0,
      "agency": "$_id.agency",
      "statusResident": "$_id.statusResident",
      "total": 1
    }
  }
])

示例here

相关问题