Update MongoDB collection using $toLower

后端 未结 6 1106
盖世英雄少女心
盖世英雄少女心 2020-12-01 05:34

I have an existing MongoDB collection containing user names. The user names contain both lower case and upper case letters.

I want to update all the user names so th

6条回答
  •  广开言路
    2020-12-01 06:05

    A little late to the party but the below answer works very well with mongo 3.4 and above First get only those records which have different case and update only those records in bulk. The performance of this query is multifold better

    var bulk = db.myCollection.initializeUnorderedBulkOp();
    var count = 0
    db.myCollection.find({userId:{$regex:'.*[A-Z]'}}).forEach(function(e) {
     var newId = e.userId.toLowerCase();   
        bulk.find({_id:e._id}).updateOne({$set:{userId: newId}})
        count++
        if (count % 500 === 0) {
            bulk.execute();
            bulk = db.myCollection.initializeUnorderedBulkOp();
            count = 0;
        }
    })
    if (count > 0)  bulk.execute();
    

提交回复
热议问题