集計


Aggregate()

パラメータ
  • [pipeline] «Array» オブジェクトの配列としての集計パイプライン

  • [model] «Model» この集計で使用するモデル。

参照

集計パイプラインを構築するために使用されるAggregateコンストラクター。このクラスを直接インスタンス化しないで、代わりに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» これ
参照

集計クエリの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を返します。.then()に似ていますが、拒否ハンドラーのみを受け取ります。awaitと互換性があります。


Aggregate.prototype.collation()

パラメータ
  • collation «Object» オプション

戻り値
  • «Aggregate» これ
参照

照合を追加します

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オプションを設定し、この集計を実行して、集計カーソルを返します。集計結果が大きすぎてメモリに収まらないため、集計結果を一度に1つずつ処理したい場合にカーソルが役立ちます。

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»

現在バインドされているモデルで集計パイプラインを実行します。

const result = await aggregate.exec();

Aggregate.prototype.explain()

パラメータ
  • [verbosity] «String»
戻り値
  • «Promise»

explainを使用して集計を実行します

Model.aggregate(..).explain()

Aggregate.prototype.facet()

パラメータ
  • facet «Object» オプション

戻り値
  • «Aggregate» これ
参照

複数の集計パイプラインを組み合わせます。

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»

.finally()がチェーンされた状態で解決されるPromiseを返す集計を実行します。

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» これ
参照

集計クエリのヒントオプションを設定します

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()

パラメータ
  • options «Object» 現在のオプションにマージするキー

    • [options.allowDiskUse] «Boolean» trueの場合、MongoDBサーバーはこの集計中にハードドライブを使用してデータを保存します

戻り値
  • «Aggregate» これ
参照

ミドルウェアまたはプラグイン用の任意のオプションを設定できます。

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» これ
参照

集計クエリのreadPreferenceオプションを設定します。

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

Aggregate.prototype.readConcern()

パラメータ
  • level «String» リストされた読み取り懸念レベルまたはそれらのエイリアスのいずれか

戻り値
  • «Aggregate» これ
参照

集計クエリのreadConcernレベルを設定します。

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

Aggregate.prototype.redact()

パラメータ
  • expression «Object» 編集オプションまたは条件式

  • [thenExpr] «String|Object» 条件のtrueの場合

  • [elseExpr] «String|Object» 条件のfalseの場合

戻り値
  • «Aggregate» これ
参照

この集計パイプラインに新しい$redact演算子を追加します。

3つの引数が指定されている場合、Mongooseはそれらをそれぞれ$cond演算子のif-then-elseでラップします。thenExprまたはelseExprが文字列の場合、$$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» これ
参照

Atlas Text Search$search ステージのヘルパー。

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

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

Aggregate.prototype.session()

パラメータ
  • session «ClientSession»
戻り値
  • «Aggregate» これ
参照

この集計のセッションを設定します。トランザクションに役立ちます。

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» これ
参照

この集計パイプラインに新しい $sort オペレーターを追加します。

オブジェクトが渡された場合、許可される値は ascdescascendingdescending1、および -1 です。

文字列が渡された場合、パス名のスペース区切りリストである必要があります。各パスのソート順は、パス名の先頭に - が付いていない限り昇順となり、- が付いている場合は降順として扱われます。

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

Aggregate.prototype.sortByCount()

パラメータ
  • arg «Object|String»
戻り値
  • «Aggregate» これ
参照

この集計パイプラインに新しい $sortByCount オペレーターを追加します。文字列のフィールド名またはパイプラインオブジェクトを受け入れます。

$sortByCount オペレーターでは、新しいルートが '$' で始まる必要があることに注意してください。指定されたフィールド名が '$' で始まっていない場合、Mongoose は '$' を先頭に追加します。

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

Aggregate.prototype.then()

パラメータ
  • [resolve] «Function» successCallback

  • [reject] «Function» errorCallback

戻り値
  • «Promise»

Promise のような then 関数を提供します。これはコールバックなしで .exec を呼び出します。await と互換性があります。

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

Aggregate.prototype.unionWith()

パラメータ
  • options «Object» 上記のリンクで説明されている $unionWith クエリへのオプション

戻り値
  • «Aggregate»
参照

この集計パイプラインに新しい $unionWith オペレーターを追加します。

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

Aggregate.prototype.unwind()

パラメータ
  • fields «String|Object|Array[String]|Array[Object]» アンワインドするフィールド(単一または複数)を、フィールド名、またはオプション付きのオブジェクトとして指定します。文字列を渡す場合、フィールド名の先頭に '$' を付けるかどうかは任意です。オブジェクトを渡す場合、path は '$' で始まる必要があります。

戻り値
  • «Aggregate»
参照

この集計パイプラインに新しいカスタムの $unwind オペレーター(単一または複数)を追加します。

$unwind オペレーターでは、パス名が '$' で始まる必要があることに注意してください。指定されたフィールドが '$' で始まっていなければ、Mongoose は '$' を先頭に追加します。

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

Aggregate.prototype[Symbol.asyncIterator]()

for/await/of ループで使用するための asyncIterator を返します。この関数を明示的に呼び出す必要はありません。JavaScript ランタイムが代わりに呼び出します。

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

Node.js 10.x は、フラグなしで async iterator をネイティブにサポートしています。Node.js 8.x では、--harmony_async_iteration フラグを使用して async iterator を有効にできます。

注: Symbol.asyncIterator が未定義の場合、この関数は設定されません。Symbol.asyncIterator が未定義の場合、お使いの Node.js バージョンが async iterator をサポートしていないことを意味します。