• 欢迎订阅我的Youtube频道
  • 欢迎加入我的电报群

Use mongo shell to batch update mongo db

网络技术 fennng 8个月前 (06-15) 315次浏览 0个评论

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);
});


峰享技术 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Use mongo shell to batch update mongo db
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址