在mongodb中的投影过程中添加对象

v9tzhpje  于 2023-10-16  发布在  Go
关注(0)|答案(1)|浏览(120)

我在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

但它并没有像预期的那样工作,有没有其他方法可以做到这一点?

relj7zay

relj7zay1#

  1. $project
  2. $group-使用combineResults数组将多个文档分组到单个文档中。
  3. $set-设置combineResults数组。对于您添加的对象,应在数组中换行。
  4. $unwind-解构combineResults数组。
  5. $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"
  }
])

Demo @ Mongo Playground

相关问题