首页 > 解决方案 > 如何覆盖当前文档 mongodb

问题描述

我有这个聚合命令,需要覆盖当前文档;

db.collection.aggregate([
  {
        $project: {
            class: "Apples",
            imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
        }
    }
])

Collection:
{
id:...
class:"Apples"
imageUrl:"..."
}

有多个文档需要更新。这是我目前附加到上述命令的内容,但它不起作用。

.forEach( doc => db.product.updateOne( { _id: doc._id }, { $set: { imageUrl: doc.imageUrl } } ) )

提前致谢!

标签: arraysmongodbmongodb-queryaggregation-framework

解决方案


您可以运行$out(用聚合结果替换整个现有集合):

db.collection.aggregate([
    {
        $project: {
            class: "Apples",
            imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
        }
    },
    { $out: "collection" }
])

或新的$merge运算符(“合并”聚合结果与现有文档):

db.collection.aggregate([
    {
        $project: {
            class: "Apples",
            imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
        }
    },
    { $merge: { into: "collection", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])

推荐阅读