mongoose常用方法(查询篇)

条件

$or 或关系
$nor 或关系取反
$gt 大于
$gte 大于等于
$lt 小于
$lte 小于等于
$ne 不等于
$in 在多个值范围内
$nin 不在多个值范围内
$all 匹配数组中多个值
$regex 正则,用于模糊查询
$size 匹配数组大小
$maxDistance 范围查询,距离(基于LBS)
$mod     取模运算
$near 邻域查询,查询附近的位置(基于LBS)
$exists 字段是否存在
$elemMatch 匹配内数组内的元素
$within 范围查询(基于LBS)
$box 范围查询,矩形范围(基于LBS)
$center 范围醒询,圆形范围(基于LBS)
$centerSphere 范围查询,球形范围(基于LBS)
$slice 查询字段集合中的元素(比如从第几个之后,第N到第M个元素

# find()

## find({$where : "this.name == 'a'"})

Model.find(conditions, [fields], [options], [callback])

注:conditions 查询条件、fields 想要查询的字段、options 、callback 回调函数
示例: 查询用户表下面名字为张三的从第二条开始的后两条文档且只需按时姓名、性别、居住地址、创建时间信息并按创建时间倒叙显示

//对象写法
userModel.find({'name':'张三'},{'name':1,'sex':1,'region':1,'createBy':1,'_id':0},{ limit:2, skip:1, sort:'-createBy.createTime'})
//链式写法
userModel.find({'name':'张三'},{'name':1,'sex':1,'region':1,'createBy':1,'_id':0}).skip(7).limit(2).sort({'createBy.createTime' : -1})

返回结果:返回结果

## find({$where : "this.name == 'a'"})

Model.$where('this.firstname === this.lastname').exec(callback)

## where复杂查询

Model
.where('age').gte(25)
.where('tags').in(['movie', 'music', 'art'])
.select('name', 'age', 'tags')
.skip(20)
.limit(10)
.asc('age')
.slaveOk()
.hint({ age: 1, name: 1 })
.run(callback);

## 查询非空字段

Model.find(conditions:{$exists:true})
Model.find(conditions:{$ne:null})

## 分页查询

Model.find(conditions).skip(pageTotal * pageNum).limit(pageTotal).sort({'_id':-1}).exec(cb);

注:condition 查询条件、pageTotal为每页显示条数、pageNum为分页数量、cb为回调函数

## 模糊查询

userModel.find({"name" : {$regex:'大虾'}})

userModel.find({"name" : /大虾/ }})

返回结果:图片描述

# findById()

Model.findById(conditions, [fields], [options], [callback])

与 Model.find 相同,但它接收文档的 _id 作为参数,返回单个文档。_id 可以是字符串或 ObjectId 对象。

# findOne()

Model.find(conditions, [fields], [options], [callback])

与 Model.find 相同,但只返回符合条件的第一个文档

批注:参考文档Mongoose基础入门

  • 2
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值