SDK數據庫 Command·聚合操作符·累記器操作符

2022-05-12 17:04 更新

AggregateCommand.addToSet(value: Expression): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。聚合運算符。向數組中添加值,如果數組中已存在該值,不執(zhí)行任何操作。它只能在 group stage 中使用。

參數

value: Expression

表達式

返回值

Object

API 說明

addToSet 語法如下:

db.command.aggregate.addToSet(<表達式>)

表達式是形如 $ + 指定字段 的字符串。如果指定字段的值是數組,那么整個數組會被當作一個元素。

示例代碼

假設集合 passages 的記錄如下:

{ "category": "web", "tags": [ "JavaScript", "CSS" ], "title": "title1" }
{ "category": "System", "tags": [ "C++", "C" ], "title": "title2" }

非數組字段

每條記錄的 category 對應值的類型是非數組,利用 addToSet 統(tǒng)計所有分類:

const $ = db.command.aggregate
db
  .collection('passages')
  .aggregate()
  .group({
    _id: null,
    categories: $.addToSet('$category')
  })
  .end()

返回的結果如下:

{ "_id": null, "categories": [ "System", "web" ] }

數組字段

每條記錄的 tags 對應值的類型是數組,數組不會被自動展開:

const $ = db.command.aggregate
db
  .collection('passages')
  .aggregate()
  .group({
    _id: null,
    tagsList: $.addToSet('$tags')
  })
  .end()

返回的結果如下:

{ "_id": null, "tagsList": [ [ "C++", "C" ], [ "JavaScript", "CSS" ] ] }

AggregateCommand.avg(value: Expression<number>): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。返回一組集合中,指定字段對應數據的平均值。

參數

value: Expression<number>

number

返回值

Object

API 說明

avg 的語法如下:

db.command.aggregate.avg(<number>)

avg 傳入的值除了數字常量外,也可以是任何最終解析成一個數字的表達式。它會忽略非數字值。

示例代碼

假設集合 students 的記錄如下:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

借助 avg 可以計算所有記錄的 score 的平均值:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: null,
    average: $.avg('$score')
  })
  .end()

返回的結果如下:

{ "_id": null, "average": 90 }

AggregateCommand.first(value: Expression): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。返回指定字段在一組集合的第一條記錄對應的值。僅當這組集合是按照某種定義排序( sort )后,此操作才有意義。

參數

value: Expression

表達式

返回值

Object

API 說明

first 的語法如下:

db.command.aggregate.first(<表達式>)

表達式是形如 $ + 指定字段 的字符串。

first 只能在 group 階段被使用,并且需要配合 sort 才有意義。

示例代碼

假設集合 students 的記錄如下:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

如果需要得到所有記錄中 score 的最小值,可以先將所有記錄按照 score 排序,然后取出第一條記錄的 first。

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .sort({
    score: 1
  })
  .group({
    _id: null,
    min: $.first('$score')
  })
  .end()

返回的數據結果如下:

{ "_id": null, "min": 80 }

AggregateCommand.last(value: Expression): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。返回指定字段在一組集合的最后一條記錄對應的值。僅當這組集合是按照某種定義排序( sort )后,此操作才有意義。

參數

value: Expression

表達式

返回值

Object

API 說明

last 的語法如下:

db.command.aggregate.last(<表達式>)

表達式是形如 $ + 指定字段 的字符串。

last 只能在 group 階段被使用,并且需要配合 sort 才有意義。

示例代碼

假設集合 students 的記錄如下:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

如果需要得到所有記錄中 score 的最大值,可以先將所有記錄按照 score 排序,然后取出最后一條記錄的 last。

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .sort({
    score: 1
  })
  .group({
    _id: null,
    max: $.last('$score')
  })
  .end()

返回的數據結果如下:

{ "_id": null, "max": 100 }

AggregateCommand.max(value: Expression): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。返回一組數值的最大值。

參數

value: Expression

表達式

返回值

Object

API 說明

max 的語法如下:

db.command.aggregate.max(<表達式>)

表達式是形如 $ + 指定字段 的字符串。

示例代碼

假設集合 students 的記錄如下:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

借助 max 可以統(tǒng)計不同組( group )中成績的最高值,代碼如下:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    maxScore: $.max('$score')
  })
  .end()

返回的數據結果如下:

{ "_id": "b", "maxScore": 100 }
{ "_id": "a", "maxScore": 96 }
```.

AggregateCommand.mergeObjects(value: Expression<document>): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。將多個文檔合并為單個文檔。

參數

value: Expression<document>

Document 表達式

返回值

Object

API 說明

使用形式如下: 在 group() 中使用時:

mergeObjects(<document>)

在其它表達式中使用時:

mergeObjects([<document1>, <document2>, ...])

示例代碼

搭配 group() 使用

假設集合 sales 存在以下文檔:

{ "_id": 1, "year": 2018, "name": "A", "volume": { "2018Q1": 500, "2018Q2": 500 } }
{ "_id": 2, "year": 2017, "name": "A", "volume": { "2017Q1": 400, "2017Q2": 300, "2017Q3": 0, "2017Q4": 0 } }
{ "_id": 3, "year": 2018, "name": "B", "volume": { "2018Q1": 100 } }
{ "_id": 4, "year": 2017, "name": "B", "volume": { "2017Q3": 100, "2017Q4": 250 } }

下面的代碼使用 mergeObjects(),將用相同 name 的文檔合并:

const $ = db.command.aggregate
db.collection('sales').aggregate()
  .group({
    _id: '$name',
    mergedVolume: $.mergeObjects('$volume')
  })
  .end()

輸出如下:

{ "_id": "A", "mergedVolume": { "2017Q1": 400, "2017Q2": 300, "2017Q3": 0, "2017Q4": 0, "2018Q1": 500, "2018Q2": 500 } }
{ "_id": "B", "mergedVolume": { "2017Q3": 100, "2017Q4": 250, "2018Q1": 100 } }

一般用法

假設集合 test 存在以下文檔:

{ "_id": 1, "foo": { "a": 1 }, "bar": { "b": 2 } }
{ "_id": 2, "foo": { "c": 1 }, "bar": { "d": 2 } }
{ "_id": 3, "foo": { "e": 1 }, "bar": { "f": 2 } }

下面的代碼使用 mergeObjects(),將文檔中的 foo 和 bar 字段合并為 foobar:

const $ = db.command.aggregate
db.collection('sales').aggregate()
  .project({
    foobar: $.mergeObjects(['$foo', '$bar'])
  })
  .end()

輸出結果如下:

{ "_id": 1, "foobar": { "a": 1, "b": 2 } }
{ "_id": 2, "foobar": { "c": 1, "d": 2 } }
{ "_id": 3, "foobar": { "e": 1, "f": 2 } }

AggregateCommand.min(value: Expression): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。返回一組數值的最小值。

參數

value: Expression

表達式

返回值

Object

API 說明

min 的語法如下:

db.command.aggregate.min(<表達式>)

表達式是形如 $ + 指定字段 的字符串。

示例代碼

假設集合 students 的記錄如下:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

借助 min 可以統(tǒng)計不同組( group )中成績的最低值,代碼如下:

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    minScore: $.min('$score')
  })
  .end()

返回的數據結果如下:

{ "_id": "b", "minScore": 80 }
{ "_id": "a", "minScore": 84 }

AggregateCommand.push(value: any): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。在 group 階段,返回一組中表達式指定列與對應的值,一起組成的數組。

參數

value: any

返回值

Object

API 說明

push 語法如下:

db.command.aggregate.push({
  <字段名1>: <指定字段1>,
  <字段名2>: <指定字段2>,
  ...
})

示例代碼

假設集合 students 的記錄如下:

{ "group": "a", "name": "stu1", "score": 84 }
{ "group": "a", "name": "stu2", "score": 96 }
{ "group": "b", "name": "stu3", "score": 80 }
{ "group": "b", "name": "stu4", "score": 100 }

借助 push 操作,對不同分組( group )的所有記錄,聚合所有數據并且將其放入一個新的字段中,進一步結構化和語義化數據。

const $ = db.command.aggregate
db
  .collection('students')
  .aggregate()
  .group({
    _id: '$group',
    students: $.push({
      name: '$name',
      score: '$score'
    })
  })
  .end()

輸出結果如下:

{ "_id": "b", "students": [{ "name": "stu3", "score": 80 }, { "name": "stu4", "score": 100 }] }
{ "_id": "a", "students": [{ "name": "stu1", "score": 84 }, { "name": "stu2", "score": 96 }] }

AggregateCommand.stdDevPop(value: Expression): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。返回一組字段對應值的標準差。

參數

value: Expression

表達式

返回值

Object

API 說明

stdDevPop 的使用形式如下:

db.command.aggregate.stdDevPop(<表達式>)

表達式傳入的是指定字段,指定字段對應的值的數據類型必須是 number ,否則結果會返回 null。

示例代碼

假設集合 students 的記錄如下:a 組同學的成績分別是84和96,b組同學的成績分別是80和100。

{ "group":"a", "score":84 }
{ "group":"a", "score":96 }
{ "group":"b", "score":80 }
{ "group":"b", "score":100 }

可以用 stdDevPop 來分別計算 a 和 b 兩組同學成績的標準差,以此來比較哪一組同學的成績更穩(wěn)定。代碼如下:

const $ = db.command.aggregate
db.collection('students').aggregate()
  .group({
    _id: '$group',
    stdDev: $.stdDevPop('$score')
  })
  .end()

返回的數據結果如下:

{ "_id": "b", "stdDev": 10 }
{ "_id": "a", "stdDev": 6 }

AggregateCommand.stdDevSamp(value: Expression): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。計算輸入值的樣本標準偏差。如果輸入值代表數據總體,或者不概括更多的數據,請改用 db.command.aggregate.stdDevPop。

參數

value: Expression

表達式

返回值

Object

API 說明

stdDevSamp 的使用形式如下:

db.command.aggregate.stdDevSamp(<表達式>)

表達式傳入的是指定字段,stdDevSamp 會自動忽略非數字值。如果指定字段所有的值均是非數字,那么結果返回 null。

示例代碼

假設集合 students 的記錄如下:

{ "score": 80 }
{ "score": 100 }

可以用 stdDevSamp 來計算成績的標準樣本偏差。代碼如下:

const $ = db.command.aggregate
db.collection('students').aggregate()
  .group({
    _id: null,
    ageStdDev: $.stdDevSamp('$score')
  })
  .end()

返回的數據結果如下:

{ "_id": null, "ageStdDev": 14.142135623730951 }

如果向集合 students 添加一條新記錄,它的 score 字段類型是 string:

{ "score": "aa" }

用上面代碼計算標準樣本偏差時,stdDevSamp 會自動忽略類型不為 number 的記錄,返回結果保持不變。


AggregateCommand.sum(value: Expression): Object

支持端:小程序 2.7.4, 云函數 0.8.1, Web

聚合操作符。計算并且返回一組字段所有數值的總和。

參數

value: Expression

表達式

返回值

Object

API 說明

sum 的使用形式如下:

db.command.aggregate.sum(<表達式>)

表達式可以傳入指定字段,也可以傳入指定字段組成的列表。sum 會自動忽略非數字值。如果字段下的所有值均是非數字,那么結果返回 0。若傳入數字常量,則當做所有記錄該字段的值都給給定常量,在聚合時相加,最終值為輸入記錄數乘以常量。

示例代碼

假設代表商品的集合 goods 的記錄如下:price 代表商品銷售額,cost 代表商品成本

{ "cost": -10, "price": 100 }
{ "cost": -15, "price": 1 }
{ "cost": -10, "price": 10 }

單獨字段

借助 sum 可以計算所有商品的銷售總和,代碼如下:

const $ = db.command.aggregate
db
  .collection('goods')
  .aggregate()
  .group({
    _id: null,
    totalPrice: $.sum('$price')
  })
  .end()

返回的數據結果如下:銷售額是 111

{ "_id": null, "totalPrice": 111 }

字段列表

如果需要計算所有商品的利潤總額,那么需要將每條記錄的 cost 和 price 相加得到此記錄對應商品的利潤。最后再計算所有商品的利潤總額。

借助 sum,代碼如下:

const $ = db.command.aggregate
db
  .collection('goods')
  .aggregate()
  .group({
    _id: null,
    totalProfit: $.sum(
      $.sum(['$price', '$cost'])
    )
  })
  .end()

返回的數據結果如下:利潤總額為 76

{ "_id": null, "totalProfit": 76 }


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號