集計
Aggregate()
Aggregate.prototype.addFields()
Aggregate.prototype.allowDiskUse()
Aggregate.prototype.append()
Aggregate.prototype.catch()
Aggregate.prototype.collation()
Aggregate.prototype.count()
Aggregate.prototype.cursor()
Aggregate.prototype.densify()
Aggregate.prototype.exec()
Aggregate.prototype.explain()
Aggregate.prototype.facet()
Aggregate.prototype.fill()
Aggregate.prototype.finally()
Aggregate.prototype.graphLookup()
Aggregate.prototype.group()
Aggregate.prototype.hint()
Aggregate.prototype.limit()
Aggregate.prototype.lookup()
Aggregate.prototype.match()
Aggregate.prototype.model()
Aggregate.prototype.near()
Aggregate.prototype.option()
Aggregate.prototype.options
Aggregate.prototype.pipeline()
Aggregate.prototype.project()
Aggregate.prototype.read()
Aggregate.prototype.readConcern()
Aggregate.prototype.redact()
Aggregate.prototype.replaceRoot()
Aggregate.prototype.sample()
Aggregate.prototype.search()
Aggregate.prototype.session()
Aggregate.prototype.skip()
Aggregate.prototype.sort()
Aggregate.prototype.sortByCount()
Aggregate.prototype.then()
Aggregate.prototype.unionWith()
Aggregate.prototype.unwind()
Aggregate.prototype[Symbol.asyncIterator]()
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» これ
参照
Aggregate.prototype.count()
パラメータ
fieldName
«String» 値としてカウントを持つ出力フィールドの名前。空でない文字列である必要があり、$で始まることはできず、.文字を含めることはできません。
戻り値
- «Aggregate»
参照
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»
Aggregate.prototype.explain()
パラメータ
[verbosity]
«String»
戻り値
- «Promise»
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
を返す集計を実行します。
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»
参照
Aggregate.prototype.hint()
パラメータ
value
«Object|String» ヒントオブジェクトまたはインデックス名
戻り値
- «Aggregate» これ
参照
Aggregate.prototype.limit()
パラメータ
num
«Number» 次のステージに渡すレコードの最大数
戻り値
- «Aggregate»
参照
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.maxTimeMS]
«Number» この集計の実行時間を制限する数値。 MongoDBのmaxTimeMS
に関するドキュメントを参照してください[options.allowDiskUse]
«Boolean» trueの場合、MongoDBサーバーはこの集計中にハードドライブを使用してデータを保存します[options.collation]
«Object» オブジェクト。Aggregate.prototype.collation()
を参照してください[options.session]
«ClientSession» ClientSession。Aggregate.prototype.session()
を参照してください
戻り値
- «Aggregate» これ
参照
ミドルウェアまたはプラグイン用の任意のオプションを設定できます。
例
const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
agg.options; // `{ allowDiskUse: true }`
Aggregate.prototype.options
型
- «property»
aggregateコマンドに渡されるオプションが含まれています。サポートされているオプションは次のとおりです。
allowDiskUse
bypassDocumentValidation
collation
comment
cursor
explain
fieldsAsRaw
hint
let
maxTimeMS
raw
readConcern
readPreference
session
writeConcern
Aggregate.prototype.pipeline()
戻り値
- «Array» 実行される操作に似た現在のパイプライン
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» これ
参照
Aggregate.prototype.readConcern()
パラメータ
level
«String» リストされた読み取り懸念レベルまたはそれらのエイリアスのいずれか
戻り値
- «Aggregate» これ
参照
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»
参照
Aggregate.prototype.sort()
パラメータ
arg
«Object|String»
戻り値
- «Aggregate» これ
参照
この集計パイプラインに新しい $sort オペレーターを追加します。
オブジェクトが渡された場合、許可される値は asc
、desc
、ascending
、descending
、1
、および -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 をサポートしていないことを意味します。