天天看点

MongoDB通过forEach循环实现Replace总结

MongoDB没有提供replace操作,需要通过forEach循环实现, 支持 JavaScript

语法

forEach循环实现Replace操作实例

1、插入一条数据
db.getCollection('blog').insert({'title': 'oldTitle'})

2、查看数据
db.getCollection('blog').find({})
/* 1 */
{
    "_id" : ObjectId("5dfb5a491699d4334f25b354"),
    "title" : "oldTitle"
}


3、使用save方式保存数据 old->new
db.getCollection("blog").find({
    _id: ObjectId("5dfb5a491699d4334f25b354")
}).forEach(function(item) {
    item.title = item.title.replace('old', "new");
    db.getCollection("blog").save(item); 
});

4、查看替换后的数据
db.getCollection('blog').find({})
/* 1 */
{
    "_id" : ObjectId("5dfb5a491699d4334f25b354"),
    "title" : "newTitle"
}

5、使用update方式更新 new->old
db.getCollection("blog").find({
    _id: ObjectId("5dfb5a491699d4334f25b354")
}).forEach(function(item) {
    title = item.title;
    title = title.replace('new', "old");
    db.getCollection("blog").update({_id:item._id},{$set:{title: title}});  
});


6、查看数据,已经修改了
db.getCollection('blog').find({})
/* 1 */
{
    "_id" : ObjectId("5dfb5a491699d4334f25b354"),
    "title" : "oldTitle"
}
      

总结

使用forEach + save方式实现replace,代码较为简洁,出错概率较低

db.getCollection("blog").find({
    _id: ObjectId("5dfb5a491699d4334f25b354")
}).forEach(function(item) {
    item.title = item.title.replace('old', "new");
    db.getCollection("blog").save(item); 
});      

参考

MongoDB replace 内容替换

继续阅读