Mongo Shell 使用过程中遇到的坑
文章目录
编写 js 脚本
js 脚本中不能包含
use关键字,需要用$ mongo mydb xxx.js这样的方式来指定数据库不能用
console.log,需要用print代替调用
ObjectId()时需要确保传进去的值为字符串,否则会出现Error: invalid object id: length使用
$set来设置数字时需要注意,mongo shell 默认会把所有数字类型的值转换成浮点型,如果你需要插入整形,你需要用NumberInt()或NumberLong()来代替。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18$ mongo mydb test.js // test.js var users = db.users.find({}); users.forEach(function(u) { // not console.log(u._id) !! // use print instead of console! print(u._id); db.users.update({ _id: ObjectId('' + u._id) // make sure the params is string }, { $set: { money: NumberInt(100) // it will be int, not float. } }); });
参考资料
文章作者 scarletsky
上次更新 2019-04-30 (95a170d)