昨天,今天,明天,每天的每天,你是否都多懂得一点点...

星期六, 六月 15, 2019

[网络技术]Use mongo shell to batch update mongo db

Updated 9000 records in a few seconds.

By mistake, I log message.chat.id as LongNumber in mongodb. I need to convert them string. With mongo shell, this can be done quite easily.

First, Login to my mongo shell

[bash]
sudo docker exec -it mongo-fengdrawbot mongo --username restheart
#Enter password to login
#switch to db collection
use messages
[/bash]

Then I used this script to save the data needs to be converted in to another collection
[javascript]
db.messages.find({"message.chat.id": {"$lt": 0}}).forEach( function (x) {
    x.message.chat.id = x.message.chat.id + "";
    db.messages_bk.save(x);
});
[/javascript]

I verified the converted data with mongo express, everything looks good. then I run the following script to update the original records.

[javascript]  

db.messages.find({"message.chat.id": {"$lt": 0}}).forEach( function (x) {
    x.message.chat.id = x.message.chat.id + "";
    db.messages.save(x);
});
[/javascript]





--
Feng

没有评论:

其它博客地址

此博客的同步博客地址: http://fengnz.wordpress.com
这里进入我的MSN SPACE.