You are viewing a single comment's thread from:

RE: Mongodb数据库快速开发

in #starnote • 13 hours ago

查询语句

//增加查找条件
or() :添加限制条件
limit(1) :查看几个
sort() :排序  
skip():跳过几个
User.find()//查询全部
  .or([{gender:2}])//查询gender为2的数据
  .sort({_id:'desc'})//倒序排列数据, 或sort({_id: -1}),asc正序  
  .limit(2)//展示两条
  .skip(2)//跳过前两个

eg:
let images = await User
     .find({user_id: req.user_id})
     .sort({_id:'desc'})
     .limit(50)

eg2:使用正则表达式,进行模式匹配查询。
db.collection.find({ field: { $regex: "example" } })
// 这个查询会返回所有符合条件的文档,其中字段 field 包含字符串 “example”。
Hivearticles.find({ title: { $regex: "比特币" } })
User.find({ name: /^A/ })  //查找名字以 "A" 开头的文档
User.find({ name: /apple/ })  //名字包含'apple'

eg3: 查询文档中数组字段的特定元素
{
  id: 1,
  arr: [
      "123",
      "456",
      "789"
  ]
}
//要查询该数组里面是否含有“456”,查询语句如下:
db.test.find({arr:{$elemMatch:{$eq:"456"}}})

{
  id: 1,
  arr: [{
    id: 1,
    name: "bonny"
  },
  {
      id: 2,
      name: "test"
  }
]}
db.test.find({arr:{$elemMatch:{name:"bonny"}}})