更多查询

miomiora大约 2 分钟MongoDBMongoDB数据库

简单的增删改查里面,查询这块名堂要多点

分页查询

单页 2 条文档,第一页 db.user.find().limit(2).skip(0)

miodb> db.user.find().limit(2).skip(2)
[
  {
    _id: ObjectId("641fbad6e438a9958f14131d"),
    name: 'hanamaru',
    age: 19,
    gender: '女'
  },
  {
    _id: ObjectId("641fbad6e438a9958f14131e"),
    name: 'makoto',
    age: 51,
    gender: '女'
  }
]

排序查询

miodb> db.user.find().sort({age:1})
[
  {
    _id: ObjectId("641fbad6e438a9958f14131c"),
    name: 'yui',
    age: 16,
    gender: '女'
  },
  {
    _id: ObjectId("641fbad6e438a9958f14131b"),
    name: 'akiyama',
    age: 17,
    gender: '女'
  },
  {
    _id: ObjectId("641fbad6e438a9958f14131d"),
    name: 'hanamaru',
    age: 19,
    gender: '女'
  },
  {
    _id: ObjectId("641fbad6e438a9958f14131e"),
    name: 'makoto',
    age: 51,
    gender: '女'
  }
]

正则查询

# 查询名字里面包含 u 的文档
miodb> db.user.find({name:/u/})
[
  {
    _id: ObjectId("641fbad6e438a9958f14131c"),
    name: 'yui',
    age: 16,
    gender: '女'
  },
  {
    _id: ObjectId("641fbad6e438a9958f14131d"),
    name: 'hanamaru',
    age: 19,
    gender: '女'
  }
]

比较查询

操作格式
等于{<key>:<value>}
小于{<key>:{$lt:<value>}}
小于或等于{<key>:{$lte:<value>}}
大于{<key>:{$gt:<value>}}
大于或等于{<key>:{$gte:<value>}}
不等于{<key>:{$ne:<value>}}
miodb> db.user.find({name:"miomiora"})
[
  {
    _id: ObjectId("641fba25e438a9958f14131a"),
    name: 'miomiora',
    age: 24,
    gender: '男'
  }
]

包含查询

miodb> db.user.find({name:{$in:["hanamaru", "yui"]}})
[
  {
    _id: ObjectId("641fbad6e438a9958f14131c"),
    name: 'yui',
    age: 16,
    gender: '女'
  },
  {
    _id: ObjectId("641fbad6e438a9958f14131d"),
    name: 'hanamaru',
    age: 19,
    gender: '女'
  }
]

条件查询

$or:[{},{},{}]$and:[{},{},{}]

查询 name 为 yui 或 makoto 的文档,并且只显示 name 和 age(0为不显示,1为显示,其中_id默认显示)

miodb> db.user.find({$or:[{name:"yui"}, {name:"makoto"}]}, {_id:0, name:1, age:1})
[ { name: 'yui', age: 16 }, { name: 'makoto', age: 51 } ]

如果 or 只是为了筛选一个字段的话用 in 更方便

上次编辑于:
贡献者: miomiora