An introduction to MongoDB pipes and an example operator

  • 2020-06-19 11:59:58
  • OfStack

An introduction to MongoDB pipes and an example operator

1 introduction

Pipes are used in Unix and Linux 1 to take the output of the current command as an argument to the next command.
The aggregation pipeline for MongoDB passes the results of the MongoDB document to the next pipeline after processing on one. Pipeline operations can be repeated.

Expression: Process input document and output. Expressions are stateless and can only be used to evaluate documents in the current aggregation pipeline, not to process other documents.

Here we introduce a few common operations in the aggregation framework:

$project: Modify the structure of the input document. It can be used to rename, add, or delete fields, or to create computed results and nested documents. $match: Used to filter data and output only eligible documents. $match USES MongoDB's standard query operations. $limit: Used to limit the number of documents returned by the MongoDB aggregation pipeline. $skip: Skips the specified number of documents in the aggregation pipeline and returns the remaining documents. $unwind: Breaks an array-type field in the document into multiple rows, each containing a value from the array. $group: Grouping documents in the collection for statistical results. $sort: Sort the input document and output it. $geoNear: Outputs ordered documents close to a geographic location of 1.

An instance of the pipe operator

1. Example of $project


db.article.aggregate(
  { $project : {
    title : 1 ,
    author : 1 ,
  }}
 );

This leaves only _id,tilte and author3 fields in the result. By default the _id field is included.


db.article.aggregate(
  { $project : {
    _id : 0 ,
    title : 1 ,
    author : 1
  }});

2. $match instance


db.articles.aggregate( [
            { $match : { score : { $gt : 70, $lte : 90 } } },
            { $group: { _id: null, count: { $sum: 1 } } }
            ] );

$match is used to get records with scores greater than 70 and less than or equal to 90, and then to send eligible records to the next phase of the $group pipeline operator for processing.

3. $skip instance


db.article.aggregate(
  { $skip : 5 });

After being processed by the $skip pipe operator, the first five documents are "filtered" out.

If you have any questions, please leave a message or go to this site community exchange discussion, thank you for reading, hope to help you, thank you for your support to this site!


Related articles: