我在DB中有如下对象
[ {
_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
但它并没有像预期的那样工作,有没有其他方法可以做到这一点?
1条答案
按热度按时间relj7zay1#
$project
$group
-使用combineResults
数组将多个文档分组到单个文档中。$set
-设置combineResults
数组。对于您添加的对象,应在数组中换行。$unwind
-解构combineResults
数组。$replaceWith
-用combineResults
对象替换输入文档。Demo @ Mongo Playground