MongoDB - 在投影期间添加对象

问题描述 投票:0回答:1

我在数据库中有一个如下所示的对象:

[
  {
    _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
  }  
]

我尝试了以下查询以获得所需的查询结果:

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
  }
]);

但是它没有按预期工作,还有其他方法吗?

mongodb mongodb-query
1个回答
2
投票
  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"
  }
])

演示@Mongo Playground

© www.soinside.com 2019 - 2024. All rights reserved.