【发布时间】:2022-01-11 14:35:05
【问题描述】:
我有这样的文件
[
{
"key": "key1",
"shops": [
{
"shopId": "S1",
"ShopName": "SN1"
},
{
"shopId": "S2",
"ShopName": "SN2"
}
]
}
]
我需要编写一个 aggerate 查询,并且我必须将一些静态元素推送到一个数组中
我试过如下
db.collection.aggregate([
{
"$match": {
"key": "key1"
}
},
{
$group: {
_id: null,
"shops": {
$push: {
"shopId": "S3",
"ShopName": "SN3"
}
}
}
},
{
"$unwind": {
"path": "$shops"
}
}
])
我的目标是在“商店”数组中添加新元素并展开文档。例外结果应如下所示
[
{
"_id": ObjectId("5a934e000102030405000000"),
"key": "key1",
"shops": {
"ShopName": "SN1",
"shopId": "S1"
}
},
{
"_id": ObjectId("5a934e000102030405000000"),
"key": "key1",
"shops": {
"ShopName": "SN2",
"shopId": "S2"
}
},
{
"_id": ObjectId("5a934e000102030405000000"),
"key": "key1",
"shops": {
"ShopName": "SN3",
"shopId": "S3"
}
}
]
你能帮帮我吗?提前谢谢你
【问题讨论】:
-
使用
$concatArrays(您不需要$group阶段 - 而不是$addFields)。
标签: mongodb mongodb-query aggregation-framework