【Node.js】mongoose教程07--排重與計數


文章目錄
  1. 1. 排重
  2. 2. 計數

排重

本文的查詢是指存儲了5個手機數據後再查詢。存儲實現見文章:【Node.js】mongoose教程—存儲

GitHub源碼鏈接:sodino#MongoDemo


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Query#distinct([field], [criteria], [callback])
Declares or executes a distict() operation.
Parameters:
[field] <String>
[criteria] <Object, Query>
[callback] <Function>
Returns:
<Query> this
See:
distinct
Passing a callback executes the query.
Example
distinct(field, conditions, callback)
distinct(field, conditions)
distinct(field, callback)
distinct(field)
distinct(callback)
distinct()

唉唉,以上的官方文檔,寫了跟沒寫有什麼區別。

field:可選項。String,用於指定需要排重的字段名稱。當field不填寫時,不能用空字符串“”代替,不填時也不出出現criteria參數。
criteria:可選項。用於指定需要排重的範圍。相當於find()的查詢條件。
callback:可選項。用於接受排重的結果。當沒有填寫該值時,可以通過鏈式調用Query.exec(callback)獲取排重結果。

在存儲實現的文章中共存了5個手機型號數據,可以用排重Query.distinct()提出這些手機都是哪個國家生產的,並且這些國家的名字只出現一次。

1
2
3
4
5
6
7
8
9
10
function findAllCountry() {
Phone.find({}).distinct('manufacturer.country').exec((err, countrys)=>{
console.log('---findAllCountry()---Remove duplicate------------------------------');
if (err) {
console.log(err);
} else {
console.log(countrys);
}
});
}

控制檯輸出:
findAllCountry


計數

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Query#count([criteria], [callback])
Specifying this query as a count query.
Parameters:
[criteria] <Object> mongodb selector
[callback] <Function>
Returns:
<Query> this
Passing a callback executes the query.
Example:
var countQuery = model.where({ 'color': 'black' }).count();
query.count({ color: 'black' }).count(callback)
query.count({ color: 'black' }, callback)
query.where('color', 'black').count(function (err, count) {
if (err) return handleError(err);
console.log('there are %d kittens', count);
})

可以使用Query.count()進行計數。

criteria:可選參數,表示要計數的查詢條件。當表示要全部計數時,可用空對象{}代替。
callback:可選參數,用於接收計數結果。

以下代碼演示統計當前的Phone數量:

1
2
3
4
5
6
7
8
9
10
11
12
13
phoneSchema.statics.printCount = function() {
// 其它的count()計算方法見以下鏈接:http://mongoosejs.com/docs/api.html#query_Query-count
// Model.count([selector], [callback])
this.count({}, (err, count) => {
console.log('---printCount()-----------------------------')
if (err) {
console.log(err);
} else {
console.log('phone count=' + count);
}
});
};

控制檯輸出:
count


下一篇mongoose教程—更新


About Sodino

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章