天天看點

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 内容替換

繼續閱讀