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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值