May 20, 2021 WeChat Mini Program Development Document
Support: Small program 2.7.4, cloud function 0.8.1, Web
The aggregation phase. Filter documents based on criteria and pass eligible documents to the next pipeline stage.
The form of match is as follows:
match(<查询条件>)
Query conditions are consistent with normal queries, you can use normal query operators, note that the match stage and other aggregation stages are different, can not use aggregate operators, can only use query operators.
// 直接使用字符串
match({
name: 'Tony Stark'
})
// 使用操作符
const _ = db.command
match({
age: _.gt(18)
})
The query operator is used within the match to support from the small program base library 2.8.3 and the cloud function SDK 1.3.0.
Suppose the collection articles have the following records:
{ "_id" : "1", "author" : "stark", "score" : 80 }
{ "_id" : "2", "author" : "stark", "score" : 85 }
{ "_id" : "3", "author" : "bob", "score" : 60 }
{ "_id" : "4", "author" : "li", "score" : 55 }
{ "_id" : "5", "author" : "jimmy", "score" : 60 }
{ "_id" : "6", "author" : "li", "score" : 94 }
{ "_id" : "7", "author" : "justan", "score" : 95 }
Here is an example of a direct match:
db.collection('articles')
.aggregate()
.match({
author: 'stark'
})
.end()
The code here tries to find that all the author fields are stark articles, so the match is as follows:
{ "_id" : "1", "author" : "stark", "score" : 80 }
{ "_id" : "2", "author" : "stark", "score" : 85 }
After match filters out the document, it can also be used with other pipeline stages.
For example, in the following example, we use group to match and calculate the number of documents with a score field greater than 80:
const _ = db.command
const $ = _.aggregate
db.collection('articles')
.aggregate()
.match({
score: _.gt(80)
})
.group({
_id: null,
count: $.sum(1)
})
.end()
The return value is as follows:
{ "_id" : null, "count" : 3 }