Aggregation Commands

MongoDB aggregate command

The aggregate command does the aggregation operation using the aggregation pipeline. The aggregation pipeline allows the user to perform data processing from a record or other source using a stage-based application sequence.

Syntax:

snippet
{
  aggregate: "<collection>" || 1, pipeline: [ <stage>, <...>],
  explain: <boolean>, allowDiskUse: <boolean>,
  cursor: <doc>,
  maxTimeMS: <int>,
  bypassDocumentValidation: <boolean>,
  readConcern: <doc>,
  collation: <doc>,
  hint: <string or doc>,
  comment: <string>,
  writeConcern: <doc>
}

Command fields:

Fields Type Description
aggregate string It contains the name of the aggregation pipeline
pipeline array The array that transforms the list of documents as a part of the aggregation pipeline.
explain boolean The explain field is optional that is used to return the information on the processing of the pipeline.
allowDiskUse boolean It enables the command to write to the temporary files.
cursor document It addresses the documents that contains the control option for the creation of the cursor object.
maxTimeMS non-negative integer It defines a time limit for the processing operations on a cursor.
Bypass
Document
Validation
boolean It is applicable only in case if you specify the out or merge aggregation stages.
readConcern document It specifies the read concern. The possible read concern levels are - local, available, majority, and linearizable.
collation document We can specify language-specific rules for string comparison using collation. Such as - rules for case and accent marks.
collation: 
{ locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>}
hint string or document It declares the index either by the index name or by the index specification document.
comment string We can declare an arbitrary string to help trace the operation through the database profiler, currentOp, and logs.
writeConcern document It is set to use the default write concern with the $out or $merge pipeline stages.

Example:

We have the following documents in the article:

snippet
{
   _id: ObjectId("52769ea0f3dc6ead47c9a1b2"),
   author: "Ankit",
   title: "rookienerd",
   tags: [ "Java Tutorial", "DBMS Tutorial", "mongodb"]
}

Now, we'll perform an aggregate operation on the articles collection to calculate the count of every distinct element within the tags array that appears within the collection.

snippet
db.runCommand( { aggregate: "articles",
   pipeline: [
      { $project: { tags: 1 } },
      { $unwind: "$tags" },
      { $group: { _id: "$tags", count: { $sum : 1 } } }
   ],
   cursor: { }
} )

MongoDB Count command

The MongoDB count command counts the number of documents in a collection or a view. It returns a document that contains the count and command status.

Syntax:

snippet
{
  count: <collection or view>,
  query: <document>,
  limit: <integer>,
  skip: <integer>,
  hint: <hint>,
  readConcern: <document>,
  collation: <document>
}

Command fields

Field Type Description
count string It is the name of the collection or view to count.
query document It is optional and used to select the document to count in the collection or view.
limit integer It is optional and used to limit the maximum number of matching documents to return.
skip integer It is optional and is used for matching documents to skip before returning results.
hint string It is used to define either the index name as a string or the index specification document.
readConcern document It specifies the read concern.
readConcern: { level: <value> }
collation document It allows us to define language-specific rules for string comparison.
Syntax:
collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

Examples:

To count the number of all the documents in the collection:

snippet
db.runCommand( { count: 'orders' } )

MongoDB Distinct Command

This command finds the distinct values for the given field across a single collection. It returns a document that contains an array of different values. The return document contains an embedded record with query statistics and the query plan.

Syntax:

snippet
distinct: "<collection>",
  key: "<field>",
  query: <query>,
  readConcern: <read concern document>,
  collation: <collation document>
  }

Command fields

Field Type Description
distinct string It is the name of the collection to query for different values
key string This is the field for which the command returns the distinct value.
query document It specifies the documents from where the distinct value will be retrieved.
readConcern document It specifies the read concern.
readConcern: { level: <value> }
collation document It allows us to define language-specific rules for string comparison.
Syntax:
collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

Example:

The following example returns different values for the field books from all documents in the library collection:

snippet
db.runCommand ( { distinct: "library", key: "books" } )

MongoDB MapReduce command

The MapReduce command allows us to run the map-reduce aggregation operations over a collection.

Syntax:

snippet
db.runCommand(
               {
                 mapReduce: <collection>,
                 map: <function>,
                 reduce: <function>,
                 finalize: <function>,
                 out: <output>,
                 query: <document>,
                 sort: <document>,
                 limit: <number>,
                 scope: <document>,
                 jsMode: <boolean>,
                 verbose: <boolean>,
                 bypassDocumentValidation: <boolean>,
                 collation: <document>,
                 writeConcern: <document>
               }
             )

Command Fields

Field Type Description
MapReduce collection It is the name of the collection on which we want to perform the map-reduce operation.
map function It is a JavaScript function that associates or maps the key-value pair.
reduce function It is a JavaScript function that reduces to a single object all the values associated with a particular key.
out string It specifies where to store the output.
query document It specifies the selection criteria to determine the documents input to the map function.
sort document It sorts the input document.
limit number It specifies a maximum number of documents for the input into the map function.
finalize function It follows the reduce method to modify the output.
scope document It is an option and declares the global variables that are accessible on the map.
jsMode boolean The jsMode specifies whether to convert intermediate data into BSON format.
verbose boolean It specifies whether to include the timing information in the result or not.
bypass
Document
Validation
boolean It enables map-reduce to bypass document validation during the operation.
collation document It allows us to specify language-specific rules for string comparison.
collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}
writeConcern document It is a document that expresses the write concern to use when outputting to a collection.

Example:

snippet
var mapFunction = function() { ... };
var reduceFunction = function(key, values) { ... };

db.runCommand(
               {
                 mapReduce: <input-collection>,
                 map: mapFunction,
                 reduce: reduceFunction,
                 out: { merge: <output-collection> },
                 query: <query>
               }
             )
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +