Skip to content

常用命令

shell
show dbs # 展示数据库
use {database} # 切换数据库
# 新增
db.{collection}.insertOne({name: "rick"}) # 插入一个文档到集合中
db.{collection}.insertMany([{name: "rick"}]) # 插入多个文档到集合中
# 查询
db.{collection}.find()
db.{collection}.find().limit(1) # 查询一条
db.{collection}.find().sort({level: 1}) # 升序排序(level 是存在的字段) -1 表示倒叙
db.{collection}.find().limit(2).skip(1) # 跳过一条数据(常用于分页查询)

db.{collection}.find({level: 3}, {name: 1, age: 1, _id: 0}) # 查询满足 {level: 3} 的用户,并且只需要返回 name 跟 age 就可以了,且明确不要 _id 参数
# 后面的对象如果是 {name: 0} 则表示,除了 name 字段,其它的都返回

# 逻辑运算符
db.{collection}.find({level: {$gt: 3 }}) #
# $gt: 大于
# $lt: 小于
# $gte: 大于等于
# $lte: 小于等于
# $eq: 等于
# $in 多个条件中的一个
# $nin 非 $in
# $exists 判断某个字段是否存在 db.{collection}.find({level: {$exists: true }}) # 有邮箱的用户(该字段存在,即便值为 null)
db.{collection}.find({level: {$in: [1, 3] }}) # 等级在1和3的用户

# $and 且运算符 db.{collection}.find({$and: [{level: {$gte: 3}}, {level: {$lte: 5}}]}) === db.{collection}.find({level: {$gte: 3, $lte: 5}})

# $not 反转 db.{collection}.find({level: {$not: {$eq: 3}}}) 等级不等于 3 的用户

# $regex db.{collection}.find({name: {$regex: /张/, $options: 'i'}}) 姓名中包含“张”的用户 (忽略大小写)
# 其它
# db.{collection}.countDocuments() # 统计数量
# db.{collection}.findOne() # 查询一条
# db.{collection}.updateOne({level: 1}, {$set: {money: 100}}) 找到level为1的用户并且新增 {money: 100}
db.spreadLinkList.update({_id:ObjectId("6086839cf1834a1070000804")},{$set:{name:"22222"}})
updateMany、deleteMany

Last updated: