is a pipeline builder for the db.collection.aggregate method and db.aggregate method. It will simplify pipelines by making them more readable and much easier to edit. It also allows you to test your pipelines on a dataset in order to verify them. Pipeline stages appear in an array. Documents pass through the stages in sequence.
const PipelineBuilder = require("mongodb-pipeline-builder").PipelineBuilder;
const { EqualityPayload, OnlyPayload, Field } = require('mongodb-pipeline-builder/helpers');
const { LessThanEqual, ArrayElemAt, Equal, Expression } = require('mongodb-pipeline-builder/operators');
import { PipelineBuilder } from 'mongodb-pipeline-builder';
import { EqualityPayload, OnlyPayload, Field } from 'mongodb-pipeline-builder/helpers';
import { LessThanEqual, ArrayElemAt, Equal, Expression } from 'mongodb-pipeline-builder/operators';
const myNewPipeline = new PipelineBuilder( 'myPagination', { debug: true } )
.Match( Expression( LessThanEqual( '$id', 20 ) ) )
.Project( OnlyPayload( 'name', 'weight' ) )
.Paging( 5, 3 ) // 5 per page, page 3
.getPipeline();
const myNewPipeline = [ {
$facet: {
docs: [
{ $match: { $expr: { $lte: ["$id", 20] } } },
{ $project: { _id: 0, name: 1, weight: 1 } },
{ $skip: 10 },
{ $limit: 5 }
],
count: [
{ $match: { $expr: { $lte: ["$id", 20] } } },
{ $project: { _id: 0, name: 1, weight: 1 } },
{ $count: "totalElements" }
]
}
} ];
const myNewPipeline = new PipelineBuilder( 'user-skills' )
.Match( Expression( Equal( '$id', 123456 ) ) )
.Lookup( EqualityPayload( 'profiles', 'profile', 'profileId', 'id' ) )
.Project( OnlyPayload( 'firstname', 'lastname', 'email' ) )
.AddFields(
Field( 'skills', ArrayElemAt( '$profile.skills', 0 ) ),
Field( 'availability', ArrayElemAt( '$profile.availability', 0 ) )
)
.Unset( 'profile' )
.getPipeline();
const myNewPipeline = [
{ $match: { $expr: { $eq: ["$id", 123456] } } },
{ $lookup: { from: "profiles", as: "profile", localField: "profileId", foreignField: "id" } },
{ $project: { _id: 0, firstname: 1, lastname: 1, email: 1 } },
{ $addFields: {
skills: { $arrayElemAt: ["$profile.skills", 0] },
availability: { $arrayElemAt: ["$profile.availability", 0] }
} },
{ $unset: "profile" }
];
is an asynchronous method that provides a very easy way to use your aggregation pipelines on a target (collection or mongoose model having the aggregation method) with pagination or without.
When you are not using pagination, the GetResult method returns a GetResultResponse object that contains two methods:
- GetDocs() to get the documents found.
- GetCount() to get the total number of documents found.
// in an asynchronous function
const result = await GetResult( target, pipeline );
result.GetDocs(); // => any[]
result.GetCount(); // => number
GetResult( target, pipeline ).then( result => {
result.GetDocs(); // => any[]
result.GetCount(); // => number
} );
You can retrieve a particular document by specifying its index as an argument of the GetDocs method.
Just pass "last" to get the last document. If the specified index is greater than the index of the last document, GetDocs() will return the last document.
// if GetDocs() returns [document0, document1, document2, document3, ..., document51]
result.GetDocs(2); // will return document to index 2, document2
result.GetDocs('last'); // will return the last document, document51
result.GetDocs(99); // will return the last document, document51
When you use paging, the GetResult method returns a GetPagingResultResponse object that contains three methods:
- GetDocs() to get the documents found.
- GetCount() to get the total number of documents found.
- GetTotalPageNumber() to get the total number of pages.
// in an asynchronous function
const result = await GetResult( target, pipeline );
result.GetDocs(); // => any[]
result.GetCount(); // => number
result.GetTotalPageNumber(); // => number
GetResult( target, pipeline ).then( result => {
result.GetDocs(); // => any[]
result.GetCount(); // => number
result.GetTotalPageNumber(); // => number
} );
[ Aggregation Pipeline Stages ]
AddFields | Bucket | BucketAuto | CollStats | Count | Facet | GeoNear | GraphLookup | Group | IndexStats | Limit | ListSessions | Lookup | Match | Merge | Out | PlanCacheStats | Project | Redact | ReplaceRoot | ReplaceWith | Sample | Search | Set | Skip | Sort | SortByCount | UnionWith | Unset | Unwind
Paging
[ Aggregation Pipeline Helpers ]
- Bucket ( GroupByPayload )
- BucketAuto ( GroupByAutoPayload )
- CurrentOp ( OpPayload )
- GeoNear ( NearPayload )
- Lookup ( ConditionPayload | EqualityPayload )
- Merge ( IntoPayload )
- Out ( DbCollPayload )
- Project ( IgnorePayload | OnlyPayload )
- Sample ( SizePayload )
- UnionWith ( CollectionPayload )
- Field: AddFields( Field ** ) | Facet( Field ** ) | Set( Field ** ) | Sort( Field ** )
- List
* If no helper is available for a stage, use stage method and pass it a valid value as a parameter.
** One or more Field helper(s) separated by a comma.
[ Aggregation Pipeline Operators ]
Absolute | Accumulator | Acos | Acosh | Add | AddToSet | AllElementsTrue | And | AnyElementTrue | ArrayElemAt | ArrayToObject | Asin | Asinh | Atan | Atan2 | Atanh | Avg | BinarySize | BsonSize | Ceil | Compare | Concat | ConcatArrays | Cond | Convert | Cos | Cosh | DateFromParts | DateFromString | DateToParts | DateToString | DayOfMonth | DayOfWeek | DayOfYear | DegreesToRadians | Divide | Equal | Exponent | Expression | Filter | First | Floor | FunctionOperator | GreaterThan | GreaterThanEqual | Hour | IfNull | In | IndexOfArray | IndexOfBytes | IndexOfCP | IsArray | IsNumber | IsoDayOfWeek | IsoWeek | IsoWeekYear | Last | LessThan | LessThanEqual | Let | Literal | Log | Log10 | Ltrim | MapOperator | Max | MergeObjects | Meta | Millisecond | Min | Minute | Mod | Month | Multiply | NaturalLog | Not | NotEqual | ObjectToArray | Or | Pow | Push | RadiansToDegrees | Rand | Range | Reduce | RegexFind | RegexFindAll | RegexMatch | ReplaceAll | ReplaceOne | ReverseArray | Round | Rtrim | SampleRate | Second | SetDifference | SetEquals | SetIntersection | SetIsSubset | SetUnion | Sin | Sinh | Size | Slice | Split | Sqrt | StdDevPop | StdDevSamp | StrCaseCmp | StrLenBytes | StrLenCP | Substr | SubstrBytes | SubstrCP | Subtract | Sum | Switch | Tan | Tanh | ToBool | ToDate | ToDecimal | ToDouble | ToInt | ToLong | ToLower | ToObjectId | ToString | ToUpper | Trim | Trunc | Type | Week | Year | Zip