MongoDB数据库常用SQL命令

迈不过友情╰ 2022-11-16 01:27 262阅读 0赞

1、db.collection.updateMany() 修改集合中的多个文档。

  1. db.getCollection('user').find({ "pId":"3332a512df604a74a72f267cf246"}).updateMany({ "pId":"c8018dd802a644a19517790336f"})

2、模糊查询

  1. db.getCollection('user').find({ name:{ $regex:"AA"}})
  2. db.getCollection('user').find({ "name":{ $regex:/AA/ }})
  3. db.getCollection('user').find({ name:/AA/})

3、查询name是否为AA,BB,CC,DD的记录

  1. db.getCollection('user').find({ "name":{ $in:["AA","BB","CC","DD"]}}) //属于 - in
  2. db.getCollection('user').find({ "name":{ $nin:["AA","BB","CC","DD"]}}) //不属于 - nin

4、按照时间排序

  1. db.getCollection('user').find({ name:{ $regex:"AA"}}).sort({ lastUpdatedTime : 1 }) //时间正序
  2. db.getCollection('user').find({ name:{ $regex:"AA"}}).sort({ lastUpdatedTime : -1 }) //时间倒序

5、字段是否存在

  1. db.getCollection('user').find({ age:{ $exists:true}})

6、对数组中的某一个元素进行查询

  1. db.getCollection('template').find({ "content.pages.questions.type":"A"})

7、limit() 和skip() 方法操作

  1. 使用limit() 方法来读取指定数量的数据,limit方法接受一个数字参数作为读取的记录条数
  2. 使用skip() 方法来跳过指定数量的数据,skip方法接受一个数字参数作为跳过的记录条数
  3. db.getCollection('user').find({ }).limit(5).skip(1) 跳过第1条,展示第2条到第6

8、时间范围查询

  1. greater than(大于)
  2. less than(小于)
  3. (>) 大于 - $gt
  4. (<) 小于 - $lt
  5. (>=) 大于等于 - $gte
  6. (<= ) 小于等于 - $lte
  7. db.getCollection('student').find({ "createdTime":{ $lt:new Date(2019,8,16)}}) //创建时间在2019.8.16之前的记录
  8. db.getCollection('student').find({ "createdTime":{ $lte:new Date(2019,8,31),$gte:new Date(2019,3,1)}}) //创建时间在2019.3.1到2019.8.31之间的记录

9、更新语句,如果你要修改多条相同的文档,则需要设置 multi 参数为 true

  1. db.getCollection('user').update({ "name":"张三"},{ $set:{ "name":"李四"}},{ multi:true})

10、具体查询文档中某个字段内包含的具体值

  1. db.getCollection('user').find({ "content.studentId.username" : "AA"})

发表评论

表情:
评论列表 (有 0 条评论,262人围观)

还没有评论,来说两句吧...

相关阅读