替换字符串中的单词

Replace a word from a string

我有 mongodb 个包含这样一个字段的文档:

Image : http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-zoom.jpg

如何用其他文本替换字符串值中的 zoom 部分以获得:

Image : http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-product2.jpg
db.myCollection.update({image: 'http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-zoom.jpg'}, {$set: {image : 'http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-product2.jpg'}})

如果您需要对多个文档多次执行此操作,则需要使用一个函数对它们进行迭代。看这里:MongoDB: Updating documents using data from the same document

您可以使用 mongo 的 forEach() cursor method to do an atomic update with the $set 运算符:

db.collection.find({}).snapshot().forEach(function(doc) {
    var updated_url = doc.Image.replace('zoom', 'product2');
    db.collection.update(
        {"_id": doc._id}, 
        { "$set": { "Image": updated_url } }
    );
});

鉴于要更新的​​集合非常大,您可以使用 bulkWrite 稍微加快速度,并重组您的更新操作以批量发送:

var ops = [];
db.collection.find({}).snapshot().forEach(function(doc) {
    ops.push({
        "updateOne": {
            "filter": { "_id": doc._id },
            "update": { "$set": { "Image": doc.Image.replace('zoom', 'product2') } }
        }
    });

    if ( ops.length === 500 ) {
        db.collection.bulkWrite(ops);
        ops = [];
    }
})

if ( ops.length > 0 )  
    db.collection.bulkWrite(ops);

如今,

  • 开始 Mongo 4.2db.collection.updateManydb.collection.update 的别名)可以接受聚合管道,最终允许根据自己的值更新字段。
  • Mongo 4.4 开始,新的聚合运算符 $replaceOne 使得替换字符串的一部分变得非常容易。
// { "Image" : "http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-zoom.jpg" }
// { "Image" : "http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-boom.jpg" }
db.collection.updateMany(
  { "Image": { $regex: /zoom/ } },
  [{
    $set: { "Image": {
      $replaceOne: { input: "$Image", find: "zoom", replacement: "product2" }
    }}
  }]
)
// { "Image" : "http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-product2.jpg" }
// { "Image" : "http://static14.com/p/Inc.5-Black-Sandals-5131-2713231-7-boom.jpg" }
  • 第一部分 ({ "Image": { $regex: /zoom/ } }) 只是为了通过过滤要更新的文档(包含 "zoom" 的文档)来加快查询速度
  • 第二部分($set: { "Image": {...)是更新聚合管道(注意方括号表示使用聚合管道):
    • $set 是一个新的聚合运算符 (Mongo 4.2),在本例中它替换了一个字段的值。
    • 新值是使用新的 $replaceOne 运算符计算的。注意 Image 是如何直接根据其自身的值 ($Image) 进行修改的。