给定一组 100 个帖子,每个帖子都有一个包含帖子内容的 body 属性,并且该内容内有图像 url,例如“http://example.com/wp-content/uploads/5.jpg http://example.com/wp-content/uploads/5.jpg"
有没有办法浏览每个帖子的正文内容,然后查找与“”匹配的任何内容http://example.com/wp-content/uploads/5.jpg http://example.com/wp-content/uploads/5.jpg“并将其替换为类似”http://amazon-bucket.aws.com/wp-content/uploads/5.jpg http://amazon-bucket.aws.com/wp-content/uploads/5.jpg"
Thanks!
不完全是,我的意思是如果您不是在寻找“精确的字符串”并且希望始终用“相同”的不同字符串替换。
本质上,您似乎正在寻找可以通过以下方式执行的文档的“正则表达式替换”.update()
。虽然有可能$regex http://docs.mongodb.org/manual/reference/operator/query/regex/搜索时,没有“捕获”或选项将捕获的部分提供给语句的“更新”部分,例如$set http://docs.mongodb.org/manual/reference/operator/update/set/.
因此,为了进行此类更新,您需要循环文档并在代码中进行修改。但是批量操作API http://docs.mongodb.org/manual/reference/method/Bulk/可以在这里提供一些帮助:
var bulk = db.collection.initializeOrderedBulkOp();
var counter = 0;
var query = { "url": { "$regex": "^http://example\.com" }};
db.collection.find(query).forEach(function(doc) {
// Inspect and replace the part of the string
bulk.find({ "_id": doc._id }).updateOne(
{ "$set": { "url": doc.url.replace("example.com","bucket.aws.com") } }
);
counter++;
// Update once every 1000 documents
if ( counter % 1000 == 0 ) {
bulk.execute();
bulk = db.collection.initializeOrderedBulkOp();
}
})
// Process any remaining
if ( counter % 1000 != 0 )
bulk.execute();
因此,这仍然需要循环,但至少每处理 1000 个文档才会将更新发送到服务器一次。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)