因此,在MongoDB3.2中(由于原因,我们还不能升级),我在这个结构中有很多文档:
// Document 1
{
"id": "record-1",
"childItems": [
"child-1",
"child-2"
],
"specLookup":[
{
"specId": "spec-1"
},
{
"specId": "spec-2"
}
]
},
// Document 2
{
"id": "record-2",
"childItems": [
"child-3"
],
"specLookup":[
{
"specId": "spec-3"
}
]
}
我需要一个聚合查询,将所有这些记录合并和操作到一个文档中,同时在一个新数组中维护所有单独的I。因此,基于上面的两个文档,我最终会得出如下结论:
{
"ids": ["record-1", "record-2"],
"childItems": [
"child-1",
"child-2",
"child-3"
],
"specIds":[
"spec-1"
"spec-2",
"spec-3"
]
}
我该怎么做?干杯!
发布于 2022-10-22 13:44:10
你可以这样做:
$group -对所有文档进行分组,添加收集所有ids、childItems和specLookup。$reduce和$concatArrays -以您想要的格式获取数据。db.collection.aggregate([
{
"$group": {
"_id": null,
"ids": {
"$addToSet": "$id"
},
"childItems": {
"$addToSet": "$childItems"
},
"specLookup": {
"$addToSet": "$specLookup.specId"
}
}
},
{
"$set": {
"childItems": {
"$reduce": {
"input": "$childItems",
"initialValue": [],
"in": {
"$concatArrays": [
"$$this",
"$$value"
]
}
}
},
"specLookup": {
"$reduce": {
"input": "$specLookup",
"initialValue": [],
"in": {
"$concatArrays": [
"$$this",
"$$value"
]
}
}
}
}
}
])https://stackoverflow.com/questions/74163837
复制相似问题