美文网首页
MongoDB replace 内容替换

MongoDB replace 内容替换

作者: 沧海2122537190 | 来源:发表于2019-07-23 15:33 被阅读0次

Mongo中现没有replace的方法,若要使用只能通过定义function的方式。
function中replace()方法可 参见javascript的replace()方法。

示例:

1.将article_title中“m”替换为“&&&&”:

db.getCollection("regex2").find({
_id:ObjectId("5d35700ad2970338fc00408e")
}).forEach(function(rep){
        a = rep.article_title;
        print("原字段:"+a);
        b = a.replace('m', "&&&&");//将“m”替换为“&&&&”
        print("替换后:"+b);
})
例一

由结果可看出,此次替换仅替换了匹配到的第一个字母,若要替换全部需在replace中应用正则。

db.getCollection("regex2").find({
    _id: ObjectId("5d35700ad2970338fc00408e")
}).forEach(function(rep) {
    a = rep.article_title;
    print("原字段:" + a);
    b = a.replace(/m/g, "&&&&");//g表示全局(global)模式
    print("替换后:" + b);
})
例二

replace默认区分大小写,若模糊大小写需利用正则修饰符“i”。

db.getCollection("regex2").find({
    _id: ObjectId("5d35700ad2970338fc00408e")
}).forEach(function(rep) {
    a = rep.article_title;
    print("原字段:" + a);
    b = a.replace(/m/i, "&&&&");//i表示不区分大小写(case-insensitive)模式
    print("替换后:" + b);
})
例三

若需将替换后的值重新写入文档中,可利用mongo语法中update
save方法。

//save
db.getCollection("regex2").find({
    _id: ObjectId("5d35700ad2970338fc00408e")
}).forEach(function(rep) {
    a = rep.article_title;
    b = a.replace(/m/i, "&&&&");
    rep.article_title=b;
    db.getCollection("regex2").save(rep);       
});
//update
db.getCollection("regex2").find({
    _id: ObjectId("5d35700ad2970338fc00408e")
}).forEach(function(rep) {
    a = rep.article_title;
    b = a.replace(/m/i, "&&&&");
    db.getCollection("regex2").update({_id:rep._id},{$set:{article_title:b}});  
})

相关文章

网友评论

      本文标题:MongoDB replace 内容替换

      本文链接:https://www.haomeiwen.com/subject/blzblctx.html