聚合


Aggregate()

參數
  • [pipeline] «Array» 作為物件陣列的聚合管道

  • [model] «Model» 用於此聚合的模型。

參見

用於建構聚合管道的聚合建構函式。請勿直接實例化此類別,請改用 Model.aggregate()

範例

const aggregate = Model.aggregate([
  { $project: { a: 1, b: 1 } },
  { $skip: 5 }
]);

Model.
  aggregate([{ $match: { age: { $gte: 21 }}}]).
  unwind('tags').
  exec();

注意

  • 傳回的文件是純 JavaScript 物件,而不是 Mongoose 文件(因為可以傳回任何形狀的文件)。

  • Mongoose 不會轉換管道階段。除非 _id 在資料庫中是字串,否則以下程式碼不會運作

    new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]); // 請改為執行此操作以轉換為 ObjectId new Aggregate([{ $match: { _id: new mongoose.Types.ObjectId('00000000000000000000000a') } }]);


Aggregate.prototype.addFields()

參數
  • arg «Object» 欄位規格

傳回
  • «Aggregate»
參見

將新的 $addFields 運算子附加到此聚合管道。需要 MongoDB v3.4+ 才能運作

範例

// adding new fields based on existing fields
aggregate.addFields({
    newField: '$b.nested'
  , plusTen: { $add: ['$val', 10]}
  , sub: {
       name: '$a'
    }
})

// etc
aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });

Aggregate.prototype.allowDiskUse()

參數
  • value «Boolean» 應告知伺服器可以在聚合期間使用硬碟儲存資料。

傳回
  • «Aggregate» this
參見

設定聚合查詢的 allowDiskUse 選項

範例

await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true);

Aggregate.prototype.append()

參數
  • ...ops «Object|Array[Object]» 要附加的運算子。可以是物件的展開,或是物件陣列的單一參數。

傳回
  • «Aggregate»

將新的運算子附加到此聚合管道

範例

aggregate.append({ $project: { field: 1 }}, { $limit: 2 });

// or pass an array
const pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
aggregate.append(pipeline);

Aggregate.prototype.catch()

參數
  • [reject] «Function»
傳回
  • «Promise»

執行聚合,傳回一個 Promise,該 Promise 將會使用 doc(s) 來解析,或使用錯誤來拒絕。類似 .then(),但僅接受拒絕處理常式。與 await 相容。


Aggregate.prototype.collation()

參數
  • collation «Object» 選項

傳回
  • «Aggregate» this
參見

新增排序規則

範例

const res = await Model.aggregate(pipeline).collation({ locale: 'en_US', strength: 1 });

Aggregate.prototype.count()

參數
  • fieldName «String» 輸出欄位的名稱,其值為計數。它必須是非空字串、不能以 $ 開頭,並且不能包含 . 字元。

傳回
  • «Aggregate»
參見

將新的 $count 運算子附加到此聚合管道。

範例

aggregate.count("userCount");

Aggregate.prototype.cursor()

參數
  • options «Object»
    • [options.batchSize] «Number» 設定游標批次大小

    • [options.useMongooseAggCursor] «Boolean» 使用實驗性的 Mongoose 特定聚合游標(用於 eachAsync() 和其他查詢游標語意)

傳回
  • «AggregationCursor» 代表此聚合的游標
參見

設定 cursor 選項並執行此聚合,傳回聚合游標。如果您想要一次處理一個聚合結果,因為聚合結果太大而無法放入記憶體,則游標非常有用。

範例

const cursor = Model.aggregate(..).cursor({ batchSize: 1000 });
cursor.eachAsync(function(doc, i) {
  // use doc
});

Aggregate.prototype.densify()

參數
  • arg «Object» $densify 運算子內容

傳回
  • «Aggregate»
參見

將新的 $densify 運算子附加到此聚合管道。

範例

 aggregate.densify({
   field: 'timestamp',
   range: {
     step: 1,
     unit: 'hour',
     bounds: [new Date('2021-05-18T00:00:00.000Z'), new Date('2021-05-18T08:00:00.000Z')]
   }
 });

Aggregate.prototype.exec()

傳回
  • «Promise»

在目前繫結的 Model 上執行聚合管道。

範例

const result = await aggregate.exec();

Aggregate.prototype.explain()

參數
  • [verbosity] «String»
傳回
  • «Promise»

使用 explain 執行聚合

範例

Model.aggregate(..).explain()

Aggregate.prototype.facet()

參數
  • facet «Object» 選項

傳回
  • «Aggregate» this
參見

合併多個聚合管道。

範例

const res = await Model.aggregate().facet({
  books: [{ groupBy: '$author' }],
  price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }]
});

// Output: { books: [...], price: [{...}, {...}] }

Aggregate.prototype.fill()

參數
  • arg «Object» $fill 運算子內容

傳回
  • «Aggregate»
參見

將新的 $fill 運算子附加到此聚合管道。

範例

 aggregate.fill({
   output: {
     bootsSold: { value: 0 },
     sandalsSold: { value: 0 },
     sneakersSold: { value: 0 }
   }
 });

Aggregate.prototype.finally()

參數
  • [onFinally] «Function»
傳回
  • «Promise»

執行聚合,傳回一個 Promise,該 Promise 將會與 .finally() 鏈結解析。

有關 JavaScript 中的 Promise finally() 的詳細資訊。


Aggregate.prototype.graphLookup()

參數
  • options «Object» 到 $graphLookup,如上述連結中所述

傳回
  • «Aggregate»
參見

將新的自訂 $graphLookup 運算子附加到此聚合管道,對集合執行遞迴搜尋。

請注意,graphLookup 最多只能消耗 100MB 的記憶體,即使指定了 { allowDiskUse: true },也不允許使用磁碟。

範例

 // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }`
 aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites

Aggregate.prototype.group()

參數
  • arg «Object» $group 運算子內容

傳回
  • «Aggregate»
參見

將新的自訂 $group 運算子附加到此聚合管道。

範例

aggregate.group({ _id: "$department" });

Aggregate.prototype.hint()

參數
  • value «Object|String» 提示物件或索引名稱

傳回
  • «Aggregate» this
參見

設定聚合查詢的 hint 選項

範例

Model.aggregate(..).hint({ qty: 1, category: 1 }).exec();

Aggregate.prototype.limit()

參數
  • num «Number» 要傳遞到下一個階段的最大記錄數

傳回
  • «Aggregate»
參見

將新的 $limit 運算子附加到此聚合管道。

範例

aggregate.limit(10);

Aggregate.prototype.lookup()

參數
  • options «Object» 到 $lookup,如上述連結中所述

傳回
  • «Aggregate»
參見

將新的自訂 $lookup 運算子附加到此聚合管道。

範例

aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });

Aggregate.prototype.match()

參數
  • arg «Object» $match 運算子內容

傳回
  • «Aggregate»
參見

將新的自訂 $match 運算子附加到此聚合管道。

範例

aggregate.match({ department: { $in: [ "sales", "engineering" ] } });

Aggregate.prototype.model()

參數
  • [model] «Model» 設定與此聚合關聯的模型。如果未提供,則傳回已儲存的模型。

傳回
  • «Model»

取得/設定此聚合將執行的模型。

範例

const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]);
aggregate.model() === MyModel; // true

// Change the model. There's rarely any reason to do this.
aggregate.model(SomeOtherModel);
aggregate.model() === SomeOtherModel; // true

Aggregate.prototype.near()

參數
  • arg «Object»
傳回
  • «Aggregate»
參見

將新的 $geoNear 運算子附加到此聚合管道。

注意

必須用作管道中的第一個運算子。

範例

aggregate.near({
  near: { type: 'Point', coordinates: [40.724, -73.997] },
  distanceField: "dist.calculated", // required
  maxDistance: 0.008,
  query: { type: "public" },
  includeLocs: "dist.location",
  spherical: true,
});

Aggregate.prototype.option()

參數
傳回
  • «Aggregate» this
參見

讓您可以設定任意選項,以用於中介軟體或外掛程式。

範例

const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
agg.options; // `{ allowDiskUse: true }`

Aggregate.prototype.options

類型
  • «property»

包含傳遞至 aggregate 命令的選項。支援的選項有


Aggregate.prototype.pipeline()

傳回
  • «Array» 目前的管道類似於將要執行的操作

傳回目前的管道

範例

MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }]

Aggregate.prototype.project()

參數
  • arg «Object|String» 欄位規格

傳回
  • «Aggregate»
參見

將新的 $project 運算子附加到此聚合管道。

也支援 Mongoose 查詢 選擇語法

範例

// include a, include b, exclude _id
aggregate.project("a b -_id");

// or you may use object notation, useful when
// you have keys already prefixed with a "-"
aggregate.project({a: 1, b: 1, _id: 0});

// reshaping documents
aggregate.project({
    newField: '$b.nested'
  , plusTen: { $add: ['$val', 10]}
  , sub: {
       name: '$a'
    }
})

// etc
aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });

Aggregate.prototype.read()

參數
  • pref «String|ReadPreference» 列出的偏好選項或其別名之一

  • [tags] «Array» 此查詢的可選標籤。

傳回
  • «Aggregate» this
參見

設定聚合查詢的 readPreference 選項。

範例

await Model.aggregate(pipeline).read('primaryPreferred');

Aggregate.prototype.readConcern()

參數
  • level «String» 列出的讀取關注層級或其別名之一

傳回
  • «Aggregate» this
參見

設定聚合查詢的讀取關注層級。

範例

await Model.aggregate(pipeline).readConcern('majority');

Aggregate.prototype.redact()

參數
  • expression «Object» 修訂選項或條件運算式

  • [thenExpr] «String|Object» 條件的 true 情況

  • [elseExpr] «String|Object» 條件的 false 情況

傳回
  • «Aggregate» this
參見

將新的 $redact 運算子附加到此聚合管道。

如果提供 3 個引數,則 Mongoose 會分別使用 $cond 運算子的 if-then-else 包裝它們。如果 thenExprelseExpr 是字串,請確保它以 $$ 開頭,例如 $$DESCEND$$PRUNE$$KEEP

範例

await Model.aggregate(pipeline).redact({
  $cond: {
    if: { $eq: [ '$level', 5 ] },
    then: '$$PRUNE',
    else: '$$DESCEND'
  }
});

// $redact often comes with $cond operator, you can also use the following syntax provided by mongoose
await Model.aggregate(pipeline).redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND');

Aggregate.prototype.replaceRoot()

參數
  • newRoot «String|Object» 將成為新根文件之欄位或文件

傳回
  • «Aggregate»
參見

將新的 $replaceRoot 運算子附加到此聚合管道。

請注意,$replaceRoot 運算子要求欄位字串以 '$' 開頭。如果您傳遞的是字串,則如果指定的欄位未以 '$' 開頭,Mongoose 將會預先加上 '$'。如果您傳遞的是物件,則您運算式中的字串將不會被變更。

範例

aggregate.replaceRoot("user");

aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } });

Aggregate.prototype.sample()

參數
  • size «Number» 要選取的隨機文件數

傳回
  • «Aggregate»
參見

將新的自訂 $sample 運算子附加到此聚合管道。

範例

aggregate.sample(3); // Add a pipeline that picks 3 random documents

Aggregate.prototype.search()

參數
  • $search «Object» 選項

傳回
  • «Aggregate» this
參見

用於 Atlas 文字搜尋$search 階段的 Helper。

範例

const res = await Model.aggregate().
 search({
   text: {
     query: 'baseball',
     path: 'plot'
   }
 });

// Output: [{ plot: '...', title: '...' }]

Aggregate.prototype.session()

參數
  • session «ClientSession»
傳回
  • «Aggregate» this
參見

設定此聚合的階段。對於 交易 非常有用。

範例

const session = await Model.startSession();
await Model.aggregate(..).session(session);

Aggregate.prototype.skip()

參數
  • num «Number» 在下一階段之前要跳過的記錄數

傳回
  • «Aggregate»
參見

將新的 $skip 運算子附加到此聚合管道。

範例

aggregate.skip(10);

Aggregate.prototype.sort()

參數
  • arg «Object|String»
傳回
  • «Aggregate» this
參見

將新的 $sort 運算子附加到此聚合管道。

如果傳入的是物件,則允許的值為 ascdescascendingdescending1-1

如果傳入的是字串,則它必須是以空格分隔的路徑名稱清單。每個路徑的排序順序都是遞增的,除非路徑名稱以 - 作為前綴,否則會被視為遞減。

範例

// these are equivalent
aggregate.sort({ field: 'asc', test: -1 });
aggregate.sort('field -test');

Aggregate.prototype.sortByCount()

參數
  • arg «Object|String»
傳回
  • «Aggregate» this
參見

將新的 $sortByCount 運算子附加到此聚合管道。接受字串欄位名稱或管道物件。

請注意,$sortByCount 運算子要求新的根以 '$' 開頭。如果指定的欄位名稱不是以 '$' 開頭,Mongoose 將會加上 '$' 前綴。

範例

aggregate.sortByCount('users');
aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })

Aggregate.prototype.then()

參數
  • [resolve] «函式» successCallback

  • [reject] «函式» errorCallback

傳回
  • «Promise»

提供一個類似 Promise 的 then 函式,它將在沒有回呼的情況下呼叫 .exec。與 await 相容。

範例

Model.aggregate(..).then(successCallback, errorCallback);

Aggregate.prototype.unionWith()

參數
  • options «物件» 對 $unionWith 查詢的設定,如上述連結所述

傳回
  • «Aggregate»
參見

將新的 $unionWith 運算子附加到此聚合管道。

範例

aggregate.unionWith({ coll: 'users', pipeline: [ { $match: { _id: 1 } } ] });

Aggregate.prototype.unwind()

參數
  • fields «字串|物件|字串陣列|物件陣列» 要展開的欄位,可以是欄位名稱,也可以是帶有選項的物件。如果傳入的是字串,則欄位名稱加上 '$' 前綴是可選的。如果傳入的是物件,則 path 必須以 '$' 開頭。

傳回
  • «Aggregate»
參見

將新的自訂 $unwind 運算子附加到此聚合管道。

請注意,$unwind 運算子要求路徑名稱以 '$' 開頭。如果指定的欄位不是以 '$' 開頭,Mongoose 將會加上 '$' 前綴。

範例

aggregate.unwind("tags");
aggregate.unwind("a", "b", "c");
aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true });

Aggregate.prototype[Symbol.asyncIterator]()

傳回一個 asyncIterator,用於 for/await/of 迴圈。您不需要明確呼叫此函式,JavaScript 執行時環境會為您呼叫它。

範例

const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
for await (const doc of agg) {
  console.log(doc.name);
}

Node.js 10.x 原生支援 async iterators,無需任何標誌。您可以使用 --harmony_async_iteration 標誌在 Node.js 8.x 中啟用 async iterators。

注意: 如果 Symbol.asyncIterator 未定義,則不會設定此函式。如果 Symbol.asyncIterator 未定義,表示您的 Node.js 版本不支援 async iterators。