我是新的mongodb,这个问题让我感到困惑,我不知道如何做到这一点。下面是mongodb的3个文档示例。
我尝试了多种方法,但仍然没有成功,谁可以帮助以下样品?它真的有可能这样做与mongodb聚合管道?要合并的关键考虑因素是机号、型号和许可证号码[
{
"INFO": "A",
"MACHINE": [
{
"NUMBER": "0001",
"MACHINE_MODEL": "A001"
},
{
"NUMBER": "0002",
"MACHINE_MODEL": "A002"
}
],
"LICENSE": [
{
"NUMBER": "1111"
},
{
"NUMBER": "2222"
}
]
},
{
"INFO": "B",
"MACHINE": [
{
"NUMBER": "0001",
"MACHINE_MODEL": "A001"
}
],
"LICENSE": [
{
"NUMBER": "1111"
}
]
},
{
"INFO": "C",
"MACHINE": [
{
"NUMBER": "0002",
"MACHINE_MODEL": "A002"
}
],
"LICENSE": [
{
"NUMBER": "2222"
}
]
},
{
"INFO": "D",
"MACHINE": [
{
"NUMBER": "0001",
"MACHINE_MODEL": "A001"
},
{
"NUMBER": "0003",
"MACHINE_MODEL": "A003"
}
],
"LICENSE": [
{
"NUMBER": "1111"
},
{
"NUMBER": "3333"
}
]
},
{
"INFO": "GG",
"MACHINE": [
{
"NUMBER": "9999",
"MACHINE_MODEL": "A999"
}
],
"LICENSE": [
{
"NUMBER": "42069"
}
]
}
]
我如何将以下结果合并/分组为新集合中的聚合和输出:
[
{
"INFO": [
"A",
"B",
"C",
"D"
],
"MACHINE": [
{
"NUMBER": "0001",
"MACHINE_MODEL": "A001"
},
{
"NUMBER": "0002",
"MACHINE_MODEL": "A002"
},
{
"NUMBER": "0003",
"MACHINE_MODEL": "A003"
}
],
"LICENSE": [
{
"NUMBER": "1111"
},
{
"NUMBER": "2222"
},
{
"NUMBER": "3333"
}
]
},
{
"INFO": "GG",
"MACHINE": [
{
"NUMBER": "9999",
"MACHINE_MODEL": "A999"
}
],
"LICENSE": [
{
"NUMBER": "42069"
}
]
}
]
不确定"GG"one_answers";A"B","C","D",但如果没有区别,这里有一个选项来对它们进行分组,删除重复项:
db.collection.aggregate([
{
$unwind: "$MACHINE"
},
{
$group: {
_id: {
NUMBER: "$MACHINE.NUMBER",
MACHINE_MODEL: "$MACHINE.MACHINE_MODEL"
},
INFO: {
"$addToSet": "$INFO"
},
LICENSE: {
"$addToSet": "$LICENSE"
},
id: {
$last: "$_id"
}
}
},
{
$group: {
_id: "$id",
"MACHINE": {
"$push": "$_id"
},
"LICENSE": {
$last: "$LICENSE"
},
"INFO": {
$last: "$INFO"
}
}
},
{
"$addFields": {
"LICENSE": {
"$reduce": {
"input": "$LICENSE",
"initialValue": [],
"in": {
"$setUnion": [
"$$this",
"$$value"
]
}
}
}
}
},
{
"$group": {
"_id": "",
"INFO": {
$push: "$INFO"
},
"LICENSE": {
$push: "$LICENSE"
},
"MACHINE": {
$push: "$MACHINE"
}
}
},
{
"$addFields": {
"LICENSE": {
"$reduce": {
"input": "$LICENSE",
"initialValue": [],
"in": {
"$setUnion": [
"$$this",
"$$value"
]
}
}
},
"INFO": {
"$reduce": {
"input": "$INFO",
"initialValue": [],
"in": {
"$setUnion": [
"$$this",
"$$value"
]
}
}
},
"MACHINE": {
"$reduce": {
"input": "$MACHINE",
"initialValue": [],
"in": {
"$setUnion": [
"$$this",
"$$value"
]
}
}
}
}
}
])
解释道:
- $unwind MACHINE对象数组
- 根据MACHINE对象的键/值分组以获得区域
- $reduce/$setUnion获得不同的许可证
- $reduce/$setUnion获取差异
- 你可以添加最后一个阶段输出到一个新的集合:{$:"theNewCollection"} 游乐场