我在数据库中有如下所示的对象
[ {
_id:12,
name:"access",
mobileNo:9153438340
},
{
_id:13,
name:"Apple",
mobileNo:9153438343
},
{
_id:14,
name:"Dell",
mobileNo:9153438344
}]
我想在投影期间添加另一个对象
{
_id:15,
name:"Skype",
mobileNo:9153438345
}
最终结果将是对象应该组合并且结果应该是
[
{
_id:12,
name:"access",
mobileNo:9153438340
},
{
_id:13,
name:"Apple",
mobileNo:9153438343
},
{
_id:14,
name:"Dell",
mobileNo:9153438344
}
{
_id:15,
name:"Skype",
mobileNo:9153438345
}
]
enter code here
我尝试了以下查询以获得所需的查询结果
db.collection.aggregate([
{
$project: {
_id: 1,
name: 1,
mobileNo: 1
// Include other fields from the existing documents as needed
}
},
{
$project: {
combinedResults: {
$concatArrays: [
[
{
_id: 15,
name: "test",
mobileNo: 9553438343
// Add other fields to the new object as needed
}
],
"$$ROOT" // Include the existing documents
]
}
}
},
{
$unwind: "$combinedResults" // Unwind the array to get separate documents
}
]);
enter code here
但是它没有按预期工作,还有其他方法吗?
$project
$group
- 使用 combineResults
数组将多个文档分组为单个文档。
$set
- 设置 combineResults
数组。对于您添加的对象,应该包装在一个数组中。
$unwind
- 解构 combineResults
数组。
$replaceWith
- 将输入文档替换为 combineResults
对象。
db.collection.aggregate([
{
$project: {
_id: 1,
name: 1,
mobileNo: 1// Include other fields from the existing documents as needed
}
},
{
$group: {
_id: null,
combinedResults: {
$push: "$$ROOT"
}
}
},
{
$set: {
combinedResults: {
$concatArrays: [
"$combinedResults",
[
{
_id: 15,
name: "test",
mobileNo: 9553438343// Add other fields to the new object as needed
}
]
]
}
}
},
{
$unwind: "$combinedResults"// Unwind the array to get separate documents
},
{
$replaceWith: "$combinedResults"
}
])