SDK數(shù)據(jù)庫 Aggregate·過濾文檔

2022-05-12 16:48 更新

Aggregate.match(object: Object): Aggregate

支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web

聚合階段。根據(jù)條件過濾文檔,并且把符合條件的文檔傳遞給下一個流水線階段。

參數(shù)

object: Object

返回值

Aggregate

API 說明

match 的形式如下:

match(<查詢條件>)

查詢條件與普通查詢一致,可以用普通查詢操作符,注意 match 階段和其他聚合階段不同,不可使用聚合操作符,只能使用查詢操作符。

// 直接使用字符串
match({
  name: 'Tony Stark'
})

// 使用操作符
const _ = db.command
match({
  age: _.gt(18)
})
match 內(nèi)使用查詢操作符從小程序基礎(chǔ)庫 2.8.3、云函數(shù) SDK 1.3.0 開始支持。

示例

假設(shè)集合 articles 有如下記錄:

{ "_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 }

匹配

下面是一個直接匹配的例子:

db.collection('articles')
  .aggregate()
  .match({
    author: 'stark'
  })
  .end()

這里的代碼嘗試找到所有 author 字段是 stark 的文章,那么匹配如下:

{ "_id" : "1", "author" : "stark", "score" : 80 }
{ "_id" : "2", "author" : "stark", "score" : 85 }

計數(shù)

match 過濾出文檔后,還可以與其他流水線階段配合使用。

比如下面這個例子,我們使用 group 進行搭配,計算 score 字段大于 80 的文檔數(shù)量:

const _ = db.command
const $ = _.aggregate
db.collection('articles')
  .aggregate()
  .match({
    score: _.gt(80)
  })
  .group({
      _id: null,
      count: $.sum(1)
  })
  .end()

返回值如下:

{ "_id" : null, "count" : 3 }


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號