连接一个数据库并进行用户密码认证授权,然后运行 mongodb shell 脚本

1
$ mongo --username auth0 --password xxx --authenticationDatabase authing_oauth --host 127.0.0.1 --port 29520 < script.js

update 第三个参数意思是 upsert——没有就创建

第四个参数是 multi——对所有符合条件的文档进行操作

下面这样,意思是有就更新,没有就新建

1
2
3
4
5
6
7
usersDb
.getCollection('users')
.update(
{ name: 'root', isDeleted: false },
userInfo,
true
)

下面这样,只有发生 upsert 动作时,才更新匹配条件的文档——即有就啥也不做,没有就创建

1
2
3
4
5
6
7
usersDb
.getCollection('users')
.update(
{ name: 'root', isDeleted: false },
{ $setOnInsert: userInfo },
true
)

创建索引

1
db.users.createIndex({ username: 1 }, { background: true });

慢查询统计

级别可以取 0,1,2 三个值,他们表示的意义如下:
   0 – 不开启
   1 – 记录慢命令 (默认为>100ms)
   2 – 记录所有命令

第二个参数是毫秒,超过此时间的查询会被记录

1
db.setProfilingLevel(1, 1000);

查询时间超过 1s 的记录

1
db.system.profile.find({ millis: { $gt: 1000 } });

查询最近的十条记录

1
db.system.profile.find().limit(10).sort({ ts: -1 }).pretty();

查询某个 collection 的记录

1
db.system.profile.find({ ns: 'mydb.table1' }).pretty();