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個元素html

# find()

## find({"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})

返回結果:返回結果this

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

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

## where複雜查詢code

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);

## 查詢非空字段htm

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爲回調函數blog

## 模糊查詢圖片

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基礎入門

相關文章
相關標籤/搜索