$ mongo
$ mongo <host>:<port>/<db_name$ -u <username$ -p <password>
$ db
$ show dbs
$ use my_db
$ show collections
$ db.serverStatus().connections
$ db.my_coll.insert({ "num": "11" })
db.my_coll.update({ num: "11" }, { $set: { num: "11", name: "john" }}, { upsert: true })
$ db.my_coll.remove({ "num": "11" })
$ db.my_coll.remove({})
$ db.my_coll.drop()
$ for (i=0; i<1000; i++) {
db.my_coll.insert({ "num": i , "num2": i * i })
}
$ db.my_coll.count()
$ db.my_coll.find()
$ db.my_coll.find({ "num": 11 })
$ db.my_coll.find({ "num": { $ne: 11 }})
$ db.my_coll.find().pretty()
$ db.my_coll.find().limit(10)
$ db.my_coll.find().skip(20)
$ db.my_coll.find().sort({ num: -1 })
$ db.my_coll.find({}, { num2: 1, _id: 0 })
Order matters - if you switch the conditions position, the result set will be [5,1000) instead of the epected [5, 11]
$ db.my_coll.find({ "num": { $gte: 5 }, "num": { $lte: 11 }})
$ db.my_coll.find({ $text: { $search: "some text" }})
$ db.my_coll.find({ $text: { $search: "wine" }}, { score: { $meta: "textScore" }, tourName: 1, _id: 0}).prety().sort({ score: { $meta: "textScore" }})
$ db.my_coll.find({ tourDescription: { $regex:/backpack/i }}, { tourName: 1, _id: 0 })
$ db.my_coll.find({ tourDescription: /backpack/i }, { tourName: 1, _id: 0 })
$ db.actors.findOne({ _id: "Brad Pitt" })
$ db.movies.findOne({ _id: "Fight Club" })
$ db.tours.count({ tourPackage: "Cycle California" })
$ db.tours.aggregate([{ $group: { _id: "$tourPackage", count: { $sum: 1 }}}])
$ db.tours.aggregate([{ $group: { _id: "$tourOrganizer.organizaerName", count: { $sum: 1 }}}])
$ db.tours.aggregate([{ $group: { _id: "$tourPackage", average: { $avg: "$tourPrice" }, count: { $sum: 1 }}}])
$ db.tours.aggregate([{ $group: {_id: "$tourPackage", average: { $avg: "$tourPrice" }, count: { $sum: 1 }}}, { $out: "prices" }])
$ db.prices.find()
$ db.my_coll.update({ "num": 11 }, { $set: { "negNum": -11 }})
$ db.my_coll.update({ "num": 11 }, { $set: { "numLst": [1, 2, 3] }})
$ db.my_coll.update({ "num": 11 }, { $addToSet: { "numLst": 4 }})
$ db.my_coll.remove({ "num": 11 })
$ db.my_coll.createIndex({ num: 1 })
$ db.my_coll.createIndex({ num: 1, { unique: true } })
$ db.my_coll.createIndex({ num: 1, { sparse: true } })
A collection can have only one text index, but it can be set-up on multiple fields (compound index).
$ db.my_coll.createIndex({ description: "text" })
$ db.my_coll.createIndex({ description: "text", comments: "text" })
$ db.my_coll.getIndexes()
$ db.my_coll.dropIndex({ "index_name" })
$ db.my_coll.find({ "num": 11 }).explain()
$ db.my_coll.find({ "num": 11 }).explain("executionStats")
$ db.runCommand({ dropDatabase: 1 })
$ mongoimport --help
$ mongoimport --db my_db --collection my_coll --file test.json
$ mongoimport --db my_db --collection my_coll --file test.csv --jsonArray
Operator | Description |
---|---|
$eq | Matches values that are equal to a specified value |
$gt | Matches values that are greater than a specified value |
$gte | Matches values that are greater than or equal to a specified value |
$in | Matches any of the values specified in an array |
$lt | Matches values that are less than a specified value |
$lte | Matches values that are less than or equal to a specified value |
Operator | Description |
---|---|
$and | Joins query clauses with a logical AND returns all documents that match the conditions of both clauses |
$not | Inverts the effect of a query expression and returns documents that do not match the query expression |
$nor | Joins query clauses with a logical NOR returns all documents that fail to match both clauses |
$or | Joins query clauses with a logical OR returns all documents that match the conditions of either clause |
Operator | Description |
---|---|
$exists | Matches documents that have the specified field |
$type | Selects documents if a field is of the specified type |
Operator | Description |
---|---|
$expr | Allows use of aggregation expressions within the query language |
$jsonSchema | Validate documents against the given JSON Schema |
$mod | Performs a modulo operation on the value of a field and selects documents with a specified result |
$regex | Selects documents where values match a specified regular expression |
$text | Performs text search |
$where | Matches documents that satisfy a JavaScript expression |
Operator | Description |
---|---|
$geoIntersects | Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports $geoIntersects |
$geoWithin | Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support $geoWithin |
$near | Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphere and 2d indexes support $near |
$nearSphere | Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support $nearSphere |
$box | Specifies a rectangular box using legacy coordinate pairs for $geoWithin queries. The 2d index supports $box |
$center | Specifies a circle using legacy coordinate pairs to $geoWithin queries when using planar geometry. The 2d index supports $center |
$centerSphere | Specifies a circle using either legacy coordinate pairs or GeoJSON format for $geoWithin queries when using spherical geometry. The 2dsphere and 2d indexes support $centerSphere |
$geometry | Specifies a geometry in GeoJSON format to geospatial query operators |
$maxDistance | Specifies a maximum distance to limit the results of $near and $nearSphere queries. The 2dsphere and 2d indexes support $maxDistance |
$minDistance | Specifies a minimum distance to limit the results of $near and $nearSphere queries. For use with 2dsphere index only |
$polygon | Specifies a polygon to using legacy coordinate pairs for $geoWithin queries. The 2d index supports $center |
$uniqueDocs | Deprecated. Modifies a $geoWithin and $near queries to ensure that even if a document matches the query multiple times, the query returns the document once |
Operator | Description |
---|---|
$all | Matches arrays that contain all elements specified in the query |
$elemMatch | Selects documents if element in the array field matches all the specified $elemMatch conditions |
$size | Selects documents if the array field is a specified size |
Operator | Description |
---|---|
$currentDate | Sets the value of a field to current date, either as a Date or a Timestamp |
$inc | Increments the value of the field by the specified amount |
$min | Only updates the field if the specified value is less than the existing field value |
$max | Only updates the field if the specified value is greater than the existing field value |
$mul | Multiplies the value of the field by the specified amount |
$rename | Renames a field |
$set | Sets the value of a field in a document |
$setOnInsert | Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents |
$unset | Removes the specified field from a document |
Operator | Description |
---|---|
$ | Acts as a placeholder to update the first element that matches the query condition |
$[] | Acts as a placeholder to update all elements in an array for the documents that match the query condition |
$[] | Acts as a placeholder to update all elements that match the arrayFilters condition for the documents that match the query condition |
$addToSet | Adds elements to an array only if they do not already exist in the set |
$pop | Removes the first or last item of an array |
$pull | Removes all array elements that match a specified query |
$push | Adds an item to an array |
$pullAll | Removes all matching values from an array |
Operator | Description |
---|---|
$each | Modifies the $push and $addToSet operators to append multiple items for array updates |
$position | Modifies the $push operator to specify the position in the array to add elements |
$slice | Modifies the $push operator to limit the size of updated arrays |
$sort | Modifies the $push operator to reorder documents stored in an array |
Operator | Description |
---|---|
$bit | Performs bitwise AND, OR, and XOR updates of integer values |
Operator | Description |
---|---|
$addFields | Adds new fields to documents. Similar to $project, $addFields reshapes each document in the stream; specifically, by adding new fields to output documents that contain both the existing fields from the input documents and the newly added fields |
$bucket | Categorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries |
$bucketAuto | Categorizes incoming documents into a specific number of groups, called buckets, based on a specified expression. Bucket boundaries are automatically determined in an attempt to evenly distribute the documents into the specified number of buckets |
$collStats | Returns statistics regarding a collection or view |
$count | Returns a count of the number of documents at this stage of the aggregation pipeline |
$facet | Processes multiple aggregation pipelines within a single stage on the same set of input documents. Enables the creation of multi-faceted aggregations capable of characterizing data across multiple dimensions, or facets, in a single stage |
$geoNear | Returns an ordered stream of documents based on the proximity to a geospatial point. Incorporates the functionality of $match, $sort, and $limit for geospatial data. The output documents include an additional distance field and can include a location identifier field |
$graphLookup | Performs a recursive search on a collection. To each output document, adds a new array field that contains the traversal results of the recursive search for that document |
$group | Groups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group. Consumes all input documents and outputs one document per each distinct group. The output documents only contain the identifier field and, if specified, accumulated fields |
$indexStats | Returns statistics regarding the use of each index for the collection |
$limit | Passes the first n documents unmodified to the pipeline where n is the specified limit. For each input document, outputs either one document (for the first n documents) or zero documents (after the first n documents) |
$listSessions | Lists all sessions that have been active long enough to propagate to the system.sessions collection |
$lookup | Performs a left outer join to another collection in the same database to filter in documents from the “joined” collection for processing |
$match | Filters the document stream to allow only matching documents to pass unmodified into the next pipeline stage. $match uses standard MongoDB queries. For each input document, outputs either one document (a match) or zero documents (no match) |
$out | Writes the resulting documents of the aggregation pipeline to a collection. To use the $out stage, it must be the last stage in the pipeline |
$project | Reshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document |
$redact | Reshapes each document in the stream by restricting the content for each document based on information stored in the documents themselves. Incorporates the functionality of $project and $match. Can be used to implement field level redaction. For each input document, outputs either one or zero documents |
$replaceRoot | Replaces a document with the specified embedded document. The operation replaces all existing fields in the input document, including the _id field. Specify a document embedded in the input document to promote the embedded document to the top level |
$sample | Randomly selects the specified number of documents from its input |
$skip | Skips the first n documents where n is the specified skip number and passes the remaining documents unmodified to the pipeline. For each input document, outputs either zero documents (for the first n documents) or one document (if after the first n documents) |
$sort | Reorders the document stream by a specified sort key. Only the order changes; the documents remain unmodified. For each input document, outputs one document |
$sortByCount | Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group |
$unwind | Deconstructs an array field from the input documents to output a document for each element. Each output document replaces the array with an element value. For each input document, outputs n documents where n is the number of array elements and can be zero for an empty array |
$currentOp | Returns information on active and/or dormant operations for the MongoDB deployment |
$listLocalSessions | Lists all active sessions recently in use on the currently connected mongos or mongod instance. These sessions may have not yet propagated to the system.sessions collection |
Operator | Description |
---|---|
$addFields | Adds new fields to documents. Outputs documents that contain all existing fields from the input documents and newly added fields |
$bucket | Categorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries |
$bucketAuto | Categorizes incoming documents into a specific number of groups, called buckets, based on a specified expression. Bucket boundaries are automatically determined in an attempt to evenly distribute the documents into the specified number of buckets |
$collStats | Returns statistics regarding a collection or view |
$count | Returns a count of the number of documents at this stage of the aggregation pipeline |
$currentOp | Returns information on active and/or dormant operations for the MongoDB deployment. To run, use the db.aggregate() method |
$facet | Processes multiple aggregation pipelines within a single stage on the same set of input documents. Enables the creation of multi-faceted aggregations capable of characterizing data across multiple dimensions, or facets, in a single stage |
$geoNear | Returns an ordered stream of documents based on the proximity to a geospatial point. Incorporates the functionality of $match, $sort, and $limit for geospatial data. The output documents include an additional distance field and can include a location identifier field |
$graphLookup | Performs a recursive search on a collection. To each output document, adds a new array field that contains the traversal results of the recursive search for that document |
$group | Groups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group. Consumes all input documents and outputs one document per each distinct group. The output documents only contain the identifier field and, if specified, accumulated fields |
$indexStats | Returns statistics regarding the use of each index for the collection |
$limit | Passes the first n documents unmodified to the pipeline where n is the specified limit. For each input document, outputs either one document (for the first n documents) or zero documents (after the first n documents) |
$listLocalSessions | Lists all active sessions recently in use on the currently connected mongos or mongod instance. These sessions may have not yet propagated to the system.sessions collection |
$listSessions | Lists all sessions that have been active long enough to propagate to the system.sessions collection |
$lookup | Performs a left outer join to another collection in the same database to filter in documents from the “joined” collection for processing |
$match | Filters the document stream to allow only matching documents to pass unmodified into the next pipeline stage. $match uses standard MongoDB queries. For each input document, outputs either one document (a match) or zero documents (no match) |
$out | Writes the resulting documents of the aggregation pipeline to a collection. To use the $out stage, it must be the last stage in the pipeline |
$project | Reshapes each document in the stream, such as by adding new fields or removing existing fields. For each input document, outputs one document |
$redact | Reshapes each document in the stream by restricting the content for each document based on information stored in the documents themselves. Incorporates the functionality of $project and $match. Can be used to implement field level redaction. For each input document, outputs either one or zero documents |
$replaceRoot | Replaces a document with the specified embedded document. The operation replaces all existing fields in the input document, including the _id field. Specify a document embedded in the input document to promote the embedded document to the top level |
$sample | Randomly selects the specified number of documents from its input |
$skip | Skips the first n documents where n is the specified skip number and passes the remaining documents unmodified to the pipeline. For each input document, outputs either zero documents (for the first n documents) or one document (if after the first n documents) |
$sort | Reorders the document stream by a specified sort key. Only the order changes; the documents remain unmodified. For each input document, outputs one document |
$sortByCount | Groups incoming documents based on the value of a specified expression, then computes the count of documents in each distinct group |
$unwind | Deconstructs an array field from the input documents to output a document for each element. Each output document replaces the array with an element value. For each input document, outputs n documents where n is the number of array elements and can be zero for an empty array |
Operator | Description |
---|---|
$abs | Returns the absolute value of a number |
$add | Adds numbers to return the sum, or adds numbers and a date to return a new date. If adding numbers and a date, treats the numbers as milliseconds. Accepts any number of argument expressions, but at most, one expression can resolve to a date |
$ceil | Returns the smallest integer greater than or equal to the specified number |
$divide | Returns the result of dividing the first number by the second. Accepts two argument expressions |
$exp | Raises e to the specified exponent |
$floor | Returns the largest integer less than or equal to the specified number |
$ln | Calculates the natural log of a number |
$log | Calculates the log of a number in the specified base |
$log10 | Calculates the log base 10 of a number |
$mod | Returns the remainder of the first number divided by the second. Accepts two argument expressions |
$multiply | Multiplies numbers to return the product. Accepts any number of argument expressions |
$pow | Raises a number to the specified exponent |
$sqrt | Calculates the square root |
$subtract | Returns the result of subtracting the second value from the first. If the two values are numbers, return the difference. If the two values are dates, return the difference in milliseconds. If the two values are a date and a number in milliseconds, return the resulting date. Accepts two argument expressions. If the two values are a date and a number, specify the date argument first as it is not meaningful to subtract a date from a number |
$trunc | Truncates a number to its integer |
Operator | Description |
---|---|
$arrayElemAt | Returns the element at the specified array index |
$arrayToObject | Converts an array of key value pairs to a document |
$concatArrays | Concatenates arrays to return the concatenated array |
$filter | Selects a subset of the array to return an array with only the elements that match the filter condition |
$in | Returns a boolean indicating whether a specified value is in an array |
$indexOfArray | Searches an array for an occurence of a specified value and returns the array index of the first occurence. If the substring is not found, returns -1 |
$isArray | Determines if the operand is an array. Returns a boolean |
$map | Applies a subexpression to each element of an array and returns the array of resulting values in order. Accepts named parameters |
$objectToArray | Converts a document to an array of documents representing key-value pairs |
$range | Outputs an array containing a sequence of integers according to user-defined inputs |
$reduce | Applies an expression to each element in an array and combines them into a single value |
$reverseArray | Returns an array with the elements in reverse order |
$size | Returns the number of elements in the array. Accepts a single expression as argument |
$slice | Returns a subset of an array |
$zip | Merge two arrays together |
Operator | Description |
---|---|
$and | Returns true only when all its expressions evaluate to true. Accepts any number of argument expressions |
$not | Returns the boolean value that is the opposite of its argument expression. Accepts a single argument expression |
$or | Returns true when any of its expressions evaluates to true. Accepts any number of argument expressions |
Operator | Description |
---|---|
$cmp | Returns 0 if the two values are equivalent, 1 if the first value is greater than the second, and -1 if the first value is less than the second |
$eq | Returns true if the values are equivalent |
$gt | Returns true if the first value is greater than the second |
$gte | Returns true if the first value is greater than or equal to the second |
$lt | Returns true if the first value is less than the second |
$lte | Returns true if the first value is less than or equal to the second |
$ne | Returns true if the values are not equivalent |
Operator | Description |
---|---|
$cond | A ternary operator that evaluates one expression, and depending on the result, returns the value of one of the other two expressions. Accepts either three expressions in an ordered list or three named parameters |
$ifNull | Returns either the non-null result of the first expression or the result of the second expression if the first expression results in a null result. Null result encompasses instances of undefined values or missing fields. Accepts two expressions as arguments. The result of the second expression can be null |
$switch | Evaluates a series of case expressions. When it finds an expression which evaluates to true, $switch executes a specified expression and breaks out of the control flow |
Operator | Description |
---|---|
$dateFromParts | Constructs a BSON Date object given the date’s constituent parts |
$dateFromString | Converts a date/time string to a date object |
$dateToParts | Returns a document containing the constituent parts of a date |
$dateToString | Returns the date as a formatted string |
$dayOfMonth | Returns the day of the month for a date as a number between 1 and 31 |
$dayOfWeek | Returns the day of the week for a date as a number between 1 (Sunday) and 7 (Saturday) |
$dayOfYear | Returns the day of the year for a date as a number between 1 and 366 (leap year) |
$hour | Returns the hour for a date as a number between 0 and 23 |
$isoDayOfWeek | Returns the weekday number in ISO 8601 format, ranging from 1 (for Monday) to 7 (for Sunday) |
$isoWeek | Returns the week number in ISO 8601 format, ranging from 1 to 53. Week numbers start at 1 with the week (Monday through Sunday) that contains the year’s first Thursday |
$isoWeekYear | Returns the year number in ISO 8601 format. The year starts with the Monday of week 1 (ISO 8601) and ends with the Sunday of the last week (ISO 8601) |
$millisecond | Returns the milliseconds of a date as a number between 0 and 999 |
$minute | Returns the minute for a date as a number between 0 and 59 |
$month | Returns the month for a date as a number between 1 (January) and 12 (December) |
$second | Returns the seconds for a date as a number between 0 and 60 (leap seconds) |
$toDate | Converts value to a Date |
$week | Returns the week number for a date as a number between 0 (the partial week that precedes the first Sunday of the year) and 53 (leap year) |
$year | Returns the year for a date as a number (e.g. 2014) |
$add | Adds numbers and a date to return a new date. If adding numbers and a date, treats the numbers as milliseconds. Accepts any number of argument expressions, but at most, one expression can resolve to a date |
$subtract | Returns the result of subtracting the second value from the first. If the two values are dates, return the difference in milliseconds. If the two values are a date and a number in milliseconds, return the resulting date. Accepts two argument expressions. If the two values are a date and a number, specify the date argument first as it is not meaningful to subtract a date from a number |
Operator | Description |
---|---|
$literal | Return a value without parsing. Use for values that the aggregation pipeline may interpret as an expression. For example, use a $literal expression to a string that starts with a $ to avoid parsing as a field path |
Operator | Description |
---|---|
$mergeObjects | Combines multiple documents into a single document |
$objectToArray | Converts a document to an array of documents representing key-value pairs |
Operator | Description |
---|---|
$allElementsTrue | Returns true if no element of a set evaluates to false, otherwise, returns false. Accepts a single argument expression |
$anyElementTrue | Returns true if any elements of a set evaluate to true; otherwise, returns false. Accepts a single argument expression |
$setDifference | Returns a set with elements that appear in the first set but not in the second set; i.e. performs a relative complement of the second set relative to the first. Accepts exactly two argument expressions |
$setEquals | Returns true if the input sets have the same distinct elements. Accepts two or more argument expressions |
$setIntersection | Returns a set with elements that appear in all of the input sets. Accepts any number of argument expressions |
$setIsSubset | Returns true if all elements of the first set appear in the second set, including when the first set equals the second set; i.e. not a strict subset. Accepts exactly two argument expressions |
$setUnion | Returns a set with elements that appear in any of the input sets |
Operator | Description |
---|---|
$concat | Concatenates any number of strings |
$dateFromString | Converts a date/time string to a date object |
$dateToString | Returns the date as a formatted string |
$indexOfBytes | Searches a string for an occurence of a substring and returns the UTF-8 byte index of the first occurence. If the substring is not found, returns -1 |
$indexOfCP | Searches a string for an occurence of a substring and returns the UTF-8 code point index of the first occurence. If the substring is not found, returns -1 |
$ltrim | Removes whitespace or the specified characters from the beginning of a string. |
$rtrim | Removes whitespace or the specified characters from the end of a string. |
$split | Splits a string into substrings based on a delimiter. Returns an array of substrings. If the delimiter is not found within the string, returns an array containing the original string |
$strLenBytes | Returns the number of UTF-8 encoded bytes in a string |
$strLenCP | Returns the number of UTF-8 code points in a string |
$strcasecmp | Performs case-insensitive string comparison and returns: 0 if two strings are equivalent, 1 if the first string is greater than the second, and -1 if the first string is less than the second |
$substr | Deprecated. Use $substrBytes or $substrCP |
$substrBytes | Returns the substring of a string. Starts with the character at the specified UTF-8 byte index (zero-based) in the string and continues for the specified number of bytes |
$substrCP | Returns the substring of a string. Starts with the character at the specified UTF-8 code point (CP) index (zero-based) in the string and continues for the number of code points specified |
$toLower | Converts a string to lowercase. Accepts a single argument expression |
$toString | Converts value to a string |
$trim | Removes whitespace or the specified characters from the beginning and end of a string |
$toUpper | Converts a string to uppercase. Accepts a single argument expression |
Operator | Description |
---|---|
$meta | Access text search metadata |
Operator | Description |
---|---|
$convert | Converts a value to a specified type |
$toBool | Converts value to a boolean |
$toDate | Converts value to a Date |
$toDecimal | Converts value to a Decimal128 |
$toDouble | Converts value to a double |
$toInt | Converts value to an integer |
$toLong | Converts value to a long |
$toObjectId | Converts value to an ObjectId |
$toString | Converts value to a string |
$type | Return the BSON data type of the field |
Operator | Description |
---|---|
$addToSet | Returns an array of unique expression values for each group. Order of the array elements is undefined |
$avg | Returns an average of numerical values. Ignores non-numeric values |
$first | Returns a value from the first document for each group. Order is only defined if the documents are in a defined order |
$last | Returns a value from the last document for each group. Order is only defined if the documents are in a defined order |
$max | Returns the highest expression value for each group |
$mergeObjects | Returns a document created by combining the input documents for each group |
$min | Returns the lowest expression value for each group |
$push | Returns an array of expression values for each group |
$stdDevPop | Returns the population standard deviation of the input values |
$stdDevSamp | Returns the sample standard deviation of the input values |
$sum | Returns a sum of numerical values. Ignores non-numeric values |
Operator | Description |
---|---|
$avg | Returns an average of the specified expression or list of expressions for each document. Ignores non-numeric values |
$max | Returns the maximum of the specified expression or list of expressions for each document |
$min | Returns the minimum of the specified expression or list of expressions for each document |
$stdDevPop | Returns the population standard deviation of the input values |
$stdDevSamp | Returns the sample standard deviation of the input values |
$sum | Returns a sum of numerical values. Ignores non-numeric values |
Operator | Description |
---|---|
$let | Defines variables for use within the scope of a subexpression and returns the result of the subexpression. Accepts named parameters. Accepts any number of argument expressions |
Operator | Description |
---|---|
$abs | Returns the absolute value of a number |
$add | Adds numbers to return the sum, or adds numbers and a date to return a new date. If adding numbers and a date, treats the numbers as milliseconds. Accepts any number of argument expressions, but at most, one expression can resolve to a date |
$addToSet | Returns an array of unique expression values for each group. Order of the array elements is undefined. Available in $group stage only |
$allElementsTrue | Returns true if no element of a set evaluates to false, otherwise, returns false. Accepts a single argument expression |
$and | Returns true only when all its expressions evaluate to true. Accepts any number of argument expressions |
$anyElementTrue | Returns true if any elements of a set evaluate to true; otherwise, returns false. Accepts a single argument expression |
$arrayElemAt | Returns the element at the specified array index |
$arrayToObject | Converts an array of key value pairs to a document |
$avg | Returns an average of numerical values. Ignores non-numeric values |
$ceil | Returns the smallest integer greater than or equal to the specified number |
$cmp | Returns: 0 if the two values are equivalent, 1 if the first value is greater than the second, and -1 if the first value is less than the second |
$concat | Concatenates any number of strings |
$concatArrays | Concatenates arrays to return the concatenated array |
$cond | A ternary operator that evaluates one expression, and depending on the result, returns the value of one of the other two expressions. Accepts either three expressions in an ordered list or three named parameters |
$convert | Converts a value to a specified type |
$dateFromParts | Constructs a BSON Date object given the date’s constituent parts |
$dateToParts | Returns a document containing the constituent parts of a date |
$dateFromString | Returns a date/time as a date object |
$dateToString | Returns the date as a formatted string |
$dayOfMonth | Returns the day of the month for a date as a number between 1 and 31 |
$dayOfWeek | Returns the day of the week for a date as a number between 1 (Sunday) and 7 (Saturday) |
$dayOfYear | Returns the day of the year for a date as a number between 1 and 366 (leap year) |
$divide | Returns the result of dividing the first number by the second. Accepts two argument expressions |
$eq | Returns true if the values are equivalent |
$exp | Raises e to the specified exponent |
$filter | Selects a subset of the array to return an array with only the elements that match the filter condition |
$first | Returns a value from the first document for each group. Order is only defined if the documents are in a defined order. Available in $group stage only |
$floor | Returns the largest integer less than or equal to the specified number |
$gt | Returns true if the first value is greater than the second |
$gte | Returns true if the first value is greater than or equal to the second |
$hour | Returns the hour for a date as a number between 0 and 23 |
$ifNull | Returns either the non-null result of the first expression or the result of the second expression if the first expression results in a null result. Null result encompasses instances of undefined values or missing fields. Accepts two expressions as arguments. The result of the second expression can be null |
$in | Returns a boolean indicating whether a specified value is in an array |
$indexOfArray | Searches an array for an occurence of a specified value and returns the array index of the first occurence. If the substring is not found, returns -1 |
$indexOfBytes | Searches a string for an occurence of a substring and returns the UTF-8 byte index of the first occurence. If the substring is not found, returns -1 |
$indexOfCP | Searches a string for an occurence of a substring and returns the UTF-8 code point index of the first occurence. If the substring is not found, returns -1 |
$isArray | Determines if the operand is an array. Returns a boolean |
$isoDayOfWeek | Returns the weekday number in ISO 8601 format, ranging from 1 (for Monday) to 7 (for Sunday) |
$isoWeek | Returns the week number in ISO 8601 format, ranging from 1 to 53. Week numbers start at 1 with the week (Monday through Sunday) that contains the year’s first Thursday |
$isoWeekYear | Returns the year number in ISO 8601 format. The year starts with the Monday of week 1 (ISO 8601) and ends with the Sunday of the last week (ISO 8601) |
$last | Returns a value from the last document for each group. Order is only defined if the documents are in a defined order. Available in $group stage only |
$let | Defines variables for use within the scope of a subexpression and returns the result of the subexpression. Accepts named parameters. Accepts any number of argument expressions |
$literal | Return a value without parsing. Use for values that the aggregation pipeline may interpret as an expression. For example, use a $literal expression to a string that starts with a $ to avoid parsing as a field path |
$ln | Calculates the natural log of a number |
$log | Calculates the log of a number in the specified base |
$log10 | Calculates the log base 10 of a number |
$lt | Returns true if the first value is less than the second |
$lte | Returns true if the first value is less than or equal to the second |
$ltrim | Removes whitespace or the specified characters from the beginning of a string |
$map | Applies a subexpression to each element of an array and returns the array of resulting values in order. Accepts named parameters |
$max | Returns the highest expression value for each group. Changed in version 3.2: Available in both $group and $project stages |
$mergeObjects | Combines multiple documents into a single document |
$meta | Access text search metadata |
$min | Returns the lowest expression value for each group |
$millisecond | Returns the milliseconds of a date as a number between 0 and 999 |
$minute | Returns the minute for a date as a number between 0 and 59 |
$mod | Returns the remainder of the first number divided by the second. Accepts two argument expressions |
$month | Returns the month for a date as a number between 1 (January) and 12 (December) |
$multiply | Multiplies numbers to return the product. Accepts any number of argument expressions |
$ne | Returns true if the values are not equivalent |
$not | Returns the boolean value that is the opposite of its argument expression. Accepts a single argument expression |
$objectToArray | Converts a document to an array of documents representing key-value pairs |
$or | Returns true when any of its expressions evaluates to true. Accepts any number of argument expressions |
$pow | Raises a number to the specified exponent |
$push | Returns an array of expression values for each group. Available in $group stage only |
$range | Outputs an array containing a sequence of integers according to user-defined inputs |
$reduce | Applies an expression to each element in an array and combines them into a single value |
$reverseArray | Returns an array with the elements in reverse order |
$rtrim | Removes whitespace or the specified characters from the end of a string |
$second | Returns the seconds for a date as a number between 0 and 60 (leap seconds) |
$setDifference | Returns a set with elements that appear in the first set but not in the second set; i.e. performs a relative complement of the second set relative to the first. Accepts exactly two argument expressions |
$setEquals | Returns true if the input sets have the same distinct elements. Accepts two or more argument expressions |
$setIntersection | Returns a set with elements that appear in all of the input sets. Accepts any number of argument expressions |
$setIsSubset | Returns true if all elements of the first set appear in the second set, including when the first set equals the second set; i.e. not a strict subset. Accepts exactly two argument expressions |
$setUnion | Returns a set with elements that appear in any of the input sets |
$size | Returns the number of elements in the array. Accepts a single expression as argument |
$slice | Returns a subset of an array |
$split | Splits a string into substrings based on a delimiter. Returns an array of substrings. If the delimiter is not found within the string, returns an array containing the original string |
$sqrt | Calculates the square root |
$stdDevPop | Returns the population standard deviation of the input values |
$stdDevSamp | Returns the sample standard deviation of the input values |
$strcasecmp | Performs case-insensitive string comparison and returns: 0 if two strings are equivalent, 1 if the first string is greater than the second, and -1 if the first string is less than the second |
$strLenBytes | Returns the number of UTF-8 encoded bytes in a string |
$strLenCP | Returns the number of UTF-8 code points in a string |
$substr | Deprecated. Use $substrBytes or $substrCP |
$substrBytes | Returns the substring of a string. Starts with the character at the specified UTF-8 byte index (zero-based) in the string and continues for the specified number of bytes |
$substrCP | Returns the substring of a string. Starts with the character at the specified UTF-8 code point (CP) index (zero-based) in the string and continues for the number of code points specified |
$subtract | Returns the result of subtracting the second value from the first. If the two values are numbers, return the difference. If the two values are dates, return the difference in milliseconds. If the two values are a date and a number in milliseconds, return the resulting date. Accepts two argument expressions. If the two values are a date and a number, specify the date argument first as it is not meaningful to subtract a date from a number |
$sum | Returns a sum of numerical values. Ignores non-numeric values |
$switch | Evaluates a series of case expressions. When it finds an expression which evaluates to true, $switch executes a specified expression and breaks out of the control flow |
$toBool | Converts value to a boolean |
$toDate | Converts value to a Date |
$toDecimal | Converts value to a Decimal128 |
$toDouble | Converts value to a double |
$toInt | Converts value to an integer |
$toLong | Converts value to a long |
$toObjectId | Converts value to an ObjectId |
$toString | Converts value to a string |
$toLower | Converts a string to lowercase. Accepts a single argument expression |
$toUpper | Converts a string to uppercase. Accepts a single argument expression |
$trim | Removes whitespace or the specified characters from the beginning and end of a string |
$trunc | Truncates a number to its integer |
$type | Return the BSON data type of the field |
$week | Returns the week number for a date as a number between 0 (the partial week that precedes the first Sunday of the year) and 53 (leap year) |
$year | Returns the year for a date as a number (e.g. 2014) |
$zip | Merge two arrays together |