node.js - 如何使用 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"}]
解决方案
你必须使用$push
累加器
db.collection.aggregate([
{ "$group": {
"_id": "$roomNo",
"availability": {
"$push": {
"slotEnd": "$slotEnd",
"slotStart": "$slotStart"
}
}
}}
])
推荐阅读
- google-sheets - 基于 if/then 在多个字段上的条件格式
- wix - 使用自定义操作的 REG_MULTI_SZ 的 MsiSetProperty
- javascript - 以后是否可以将值绑定到函数中的 Vue 元素?
- plot - Jzy3d 3d插值图不渲染
- excel - 如果所有三个条件都完全满足,那么“ok”
- python - 在 Python 中处理嵌套的 JSON
- r - 如何在 R 中使用 ggplot2 将 y 轴更改为百分比?
- javascript - 无法读取未定义类型错误的属性“订阅”
- c - 仿射代码错误
- html - CSS - 如何在背景图像之上获取 div?