Use mongo shell to batch update mongo db

  • fennng 

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

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

Then I used this script to save the data needs to be converted in to another collection

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

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

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

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注