Mongoose 一些查詢方法


分針網每日分享:Mongoose 一些查詢方法
 
 
Mongoose 模型提供了 find, findOne, 和 findById 方法用於文檔查詢。
 
1. Model.find
 
Model.find(query, fields, options, callback)// fields 和 options 都是可選參數
 
簡單查詢
 
Model.find({ 'csser.com': 5 }, function (err, docs) { // docs 是查詢的結果數組 });
 
只查詢指定鍵的結果
 
Model.find({}, ['first', 'last'], function (err, docs) { // docs 此時只包含文檔的部分鍵值})
 
2. Model.findOne
 
與 Model.find 相同,但只返回單個文檔
Model.findOne({ age: 5}, function (err, doc){ // doc 是單個文檔});
 
3. Model.findById
 
與 findOne 相同,但它接收文檔的 _id 作為參數,返回單個文檔。_id 可以是字符串或 ObjectId 對象。
Model.findById(obj._id, function (err, doc){ // doc 是單個文檔});
 
4. Model.count
 
返回符合條件的文檔數。
Model.count(conditions, callback);
 
5. Model.remove
 
刪除符合條件的文檔。
Model.remove(conditions, callback);
 
6. Model.distinct
 
查詢符合條件的文檔並返回根據鍵分組的結果。
Model.distinct(field, conditions, callback);
 
7. Model.where
 
當查詢比較復雜時,用 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);
 
8. Model.$where
 
有時我們需要在 MongoDB中使用JavaScript表達式進行查詢,這時可以用 find({$where : javascript}) 方式,$where 是一種快捷方式,並支持鏈式調用查詢。
Model.$where('this.firstname === this.lastname').exec(callback)
 
9. Model.update
 
使用 update 子句更新符合指定條件的文檔,更新數據在發送到數據庫服務器之前會改變模型的類型。
 
var conditions = { name: 'borne' }
, update = { $inc: { visits: 1 }}
, options = { multi: true };
 
Model .update(conditions, update, options, callback)
 
注意:為了向后兼容,所有頂級更新鍵如果不是原子操作命名的,會統一被按 $set 操作處理,例如:
 
var query = { name: 'borne' };
Model .update(query, { name: 'jason borne' }, options, callback)
 
// 會被這樣發送到數據庫服務器
 
Model .update(query, { $set: { name: 'jason borne' }}, options, callback)
 
10. 查詢 API
 
如果不提供回調函數,所有這些方法都返回 Query 對象,它們都可以被再次修改(比如增加選項、鍵等),直到調用 exec 方法。
 
var query = Model.find({});
 
query .where('field', 5);
query .limit(5);
query .skip(100);
 
query .exec(function (err, docs) {
// called when the `query.complete` or `query.error` are called
// internally
});
 
  本文轉自: http://www.f-z.cn/id/274


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM