【问题标题】:How to overwrite current document mongodb如何覆盖当前文档 mongodb
【发布时间】:2020-01-06 02:08:59
【问题描述】:

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

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

提前致谢!

【问题讨论】:

    标签: arrays mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您可以运行$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" } }
    ])
    

    【讨论】:

    • 它们只有 ~10 的 2 个字段。我尝试了第一个,但它只用这两个字段替换了所有内容。
    • @Kingswoop 使用$addFields 而不是$project(将替换现有字段)
    猜你喜欢
    • 1970-01-01
    • 2014-08-26
    • 2011-11-29
    • 2013-11-25
    • 2015-05-08
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    相关资源
    最近更新 更多