首页 > 解决方案 > 如何使用 Mongodb 对一个数组中具有不同值的特定属性的同名文档进行分组?

问题描述

如果我有这些对象:

{
    "_id" : ObjectId("5caf2c1642e3731464c2c79d"),
    "requested" : [],
    "roomNo" : "E0-1-09",
    "capacity" : 40,
    "venueType" : "LR(M)",
    "seatingType" : "TB",
    "slotStart" : "8:30AM",
    "slotEnd" : "9:50AM",
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5caf2deb4a7f5222305b55d5"),
    "requested" : [],
    "roomNo" : "E0-1-09",
    "capacity" : 40,
    "venueType" : "LR(M)",
    "seatingType" : "TB",
    "slotStart" : "10:00AM",
    "slotEnd" : "11:20AM",
    "__v" : 0
}

是否有可能在 mongodb 中使用聚合获得类似的东西?

[{ roomNo: "E0-1-09" , availability : [{slotStart : "8:30AM", slotEnd: "9:50AM"} ,
{slotStart: "10:00AM", slotEnd : "11:20AM"}]

我目前使用的是什么:

db.getDB().collection(collection).aggregate([
  { $group: {_id:{roomNo: "$roomNo", availability :[{slotStart:"$slotStart", slotEnd:"$slotEnd"}]}}}
     ])

实际上像这样两次获得它:

[{ roomNo: "E0-1-09" , availability : [{slotStart : "8:30AM", slotEnd: "9:50AM"}]
[{ roomNo: "E0-1-09" , availability : [{slotStart: "10:00AM", slotEnd : "11:20AM"}]

标签: node.jsmongodbaggregation-framework

解决方案


你必须使用$push累加器

db.collection.aggregate([
  { "$group": {
    "_id": "$roomNo",
    "availability": {
      "$push": {
        "slotEnd": "$slotEnd",
        "slotStart": "$slotStart"
      }
    }
  }}
])

推荐阅读