MONGODB OPERATORS

MONGODB OPERATORS

Comparison Operator
$eq
$ne
$gt
$gte
$in
$lt
$lte
$nin

Logical Operator
$and
$or
$not
$nor

Element Operator
$exists
$all
$elemMatch
$size

Evaluation Operator
$expr
$mod
$elemMatch
$slice
$text:$search


Set Top-Level Field Operator
$min
$max
$mul
$round
$multiply
$mul
$rename



updateOne()
updateMany()
limit()
skip()
sort()
find()
runCommand()
createCommand()
deleteOne()
deleteMany()
drop()
insertOne()
insertMany()
aggregate([])


With runCommand
distinct
count

Aggregation Pipeline Operators
$abs
$add
$subtract
$multiply
$divide
$ceil
$floor
$mod
$pow
$round
$sqrt
$trunc
$arrayElemAt
$arrayToObject
$concatArrays
$in
$indexOfArray
$range
$reverseArray
$size
$slice

MongoDB Query and Projection Operator

The MongoDB query operator includes comparison, logical, element, evaluation, Geospatial, array,
bitwise, and comment operators.

MongoDB Comparison Operators


$eq
The $eq specifies the equality condition. It matches documents where the value of a field equals the
specified value.
Syntax:
1. { <field> : { $eq: <value> } }
Example:
1. db.books.find ( { price: { $eq: 300 } } )
The above example queries the books collection to select all documents where the value of the price
filed equals 300.



$gt
The $gt chooses a document where the value of the field is greater than the specified value.
Syntax:
1. { field: { $gt: value } }
Example:
1. db.books.find ( { price: { $gt: 200 } } )



$gte
The $gte choose the documents where the field value is greater than or equal to a specified value.
Syntax:
1. { field: { $gte: value } }
Example:1. db.books.find ( { price: { $gte: 250 } } )



$in
The $in operator choose the documents where the value of a field equals any value in the specified
array.
Syntax:
1. { filed: { $in: [ <value1>, <value2>, ……] } }
Example:
1. db.books.find( { price: { $in: [100, 200] } } )




$lt
The $lt operator chooses the documents where the value of the field is less than the specified value.
Syntax:
1. { field: { $lt: value } }
Example:
1. db.books.find ( { price: { $lt: 20 } } )




$lte
The $lte operator chooses the documents where the field value is less than or equal to a specified value.
Syntax:
1. { field: { $lte: value } }
Example:
1. db.books.find ( { price: { $lte: 250 } } )




$ne
The $ne operator chooses the documents where the field value is not equal to the specified value.
Syntax:
1. { <field>: { $ne: <value> } }
Example:
1. db.books.find ( { price: { $ne: 500 } } ) $nin




$nin
The $nin operator chooses the documents where the field value is not in the specified array or does not
exist.
Syntax:
1. { field : { $nin: [ <value1>, <value2>, .... ] } }
Example:
1. db.books.find ( { price: { $nin: [ 50, 150, 200 ] } } )




MongoDB Logical Operator


$and
The $and operator works as a logical AND operation on an array. The array should be of one or more
expressions and chooses the documents that satisfy all the expressions in the array.
Syntax:
1. { $and: [ { <exp1> }, { <exp2> }, ....]}
Example:
1. db.books.find ( { $and: [ { price: { $ne: 500 } }, { price: { $exists: true } } ] } )



$not
The $not operator works as a logical NOT on the specified expression and chooses the documents that
are not related to the expression.
Syntax:
1. { field: { $not: { <operator-expression> } } }
Example:
1. db.books.find ( { price: { $not: { $gt: 200 } } } )



$nor
The $nor operator works as logical NOR on an array of one or more query expression and chooses the
documents that fail all the query expression in the array.
Syntax:
1. { $nor: [ { <expression1> } , { <expresion2> } , ..... ] } Example:
1. db.books.find ( { $nor: [ { price: 200 }, { sale: true } ] } )



$or
It works as a logical OR operation on an array of two or more expressions and chooses documents that
meet the expectation at least one of the expressions.
Syntax:
1. { $or: [ { <exp_1> }, { <exp_2> }, ... , { <exp_n> } ] }
Example:
1. db.books.find ( { $or: [ { quantity: { $lt: 200 } }, { price: 500 } ] } )




MongoDB Element Operator

$exists
The exists operator matches the documents that contain the field when Boolean is true. It also matches
the document where the field value is null.
Syntax:
1. { field: { $exists: <boolean> } }
Example:
1. db.books.find ( { qty: { $exists: true, $nin: [ 5, 15 ] } } )




$all
It chooses the document where the value of a field is an array that contains all the specified elements.
Syntax:
1. { <field>: { $all: [ <value1> , <value2> ... ] } }
Example:
1. db.books.find( { tags: { $all: [ "Java", "MongoDB", "RDBMS" ] } } )




$elemMatch(Query)
The $elemMatch() operator matches documents that contain an array field with at least one element that matches all the specified query criteria.
1. { <field>: { $elemMatch: { <query1> , <query2>, ... } } }
Example:
{ "name" : "c++book", "page" : 250, "price" : [ 200, 150, 300, 500 ] }
{ "name" : "javabook", "page" : 450, "price" : [ 20, 1500, 350, 600 ] }
{ "name" : "aspcookbook", "page" : 850, "price" : [ 900, 250 ] }
{ "name" : "mathsbook", "page" : 1150, "price": [ 200, 450, 300, 500, 900 ] }

> db.books.find({price:{$elemMatch:{$gt:1000,$lt:2000}}});
{ "_id" : ObjectId("6380f49b697633314268a0d3"), "name" : "javabook", "page" : 450, "price" : [
20, 1500, 350, 600 ] }

Q. If you want to find all books where the price array contains an element that matches specific conditions, such as being greater than or equal to 8.99 and less than 10.00, you would use $elemMatch:
>  db.books.find( { price: { $elemMatch: { $gte: 6.99,  $lt:18.99}}  })
[
  {
    _id: ObjectId('66a48811f5977479b71f340f'),
    title: 'Book One',
    author: 'Author One',
    page: 450,
    price: [ 12.99, 13.99, 15.99, 17.99, 19.99 ]
  },
  {
    _id: ObjectId('66a48811f5977479b71f3410'),
    title: 'Book Two',
    author: 'Author Two',
    page: 300,
    price: [ 8.99, 9.99, 10.99, 11.99 ]
  },
  {
    _id: ObjectId('66a48811f5977479b71f3412'),
    title: 'Book Four',
    author: 'Author Four',
    page: 200,
    price: [ 5.99, 6.99, 7.99, 8.99 ]
  }
]





$size
It selects any array with the number of the element specified by the argument.
Syntax:
1. db.collection.find( { field: { $size: 2 } } );
Example:
> db.empinfo.find({skills:{$size:2}});
{ "_id" : ObjectId("63b3eff78879cc459a627672"), "name" : "Seema", "age" : 18, "loc" : "kolkata", "gen" : "female", "skills" : [
"python", "php" ] }
{ "_id" : ObjectId("63b7ca2e1587f15a7fce0b15"), "name" : "Rita", "age" : 35, "loc" : "patna", "gen" : "female", "skills" : [ "react",
"angular" ] }




MongoDB Evaluation Operator


$expr
$expr can build query expressions that compare fields from within the same documents.
Syntax:
{ $expr: { <expression> } }
Example:
> db.expenses.insertMany([ {"category": "food", "budget": 400, "spent": 450}, {"category": "drinks", "budget": 100, "spent": 150 }, { "category": "cloths", "budget": 100, "spent":50}, {"category":"misc", "budget": 500, "spent": 300}, {"category": "travel", "budget":200, "spent": 650 }  ])
> db.monthlyBudget.find ();
{ "_id" : 1, "category" : "food", "budget" : 400, "spent" : 450 }
{ "_id" : 2, "category" : "drinks", "budget" : 100, "spent" : 150 }
{ "_id" : 3, "category" : "clothes", "budget" : 100, "spent" : 50 }
{ "_id" : 4, "category" : "misc", "budget" : 500, "spent" : 300 }
{ "_id" : 5, "category" : "travel", "budget" : 200, "spent" : 650 }
> db.monthlyBudget.find( { $expr: { $gt: [ "$spent" , "$budget" ] } } )
{ "_id" : 1, "category" : "food", "budget" : 400, "spent" : 450 }
{ "_id" : 2, "category" : "drinks", "budget" : 100, "spent" : 150 }
{ "_id" : 5, "category" : "travel", "budget" : 200, "spent" : 650 }
> db.monthlyBudget.find( { $expr: { $lt: [ "$spent" , "$budget" ] } } )
{ "_id" : 3, "category" : "clothes", "budget" : 100, "spent" : 50 }
{ "_id" : 4, "category" : "misc", "budget" : 500, "spent" : 300 }
>






$mod
The mod operator selects the document where the value of a field is divided by a divisor has the
specified remainder.
Syntax:
1. { field: { $mod: [ divisor, remainder ] } }
Example:
> db.monthlyBudget.find({spent:{$mod:[5,0]}}); //spent%5==0
{ "_id" : 1, "category" : "food", "budget" : 400, "spent" : 450 }{ "_id" : 2, "category" : "drinks", "budget" : 100, "spent" : 150 }
{ "_id" : 3, "category" : "clothes", "budget" : 100, "spent" : 50 }
{ "_id" : 4, "category" : "misc", "budget" : 500, "spent" : 300 }
{ "_id" : 5, "category" : "travel", "budget" : 200, "spent" : 650 }
> db.monthlyBudget.find({ spent:{ $mod:[11,6] } }); //spent%11==6
{ "_id" : 3, "category" : "clothes", "budget" : 100, "spent" : 50 }
> db.monthlyBudget.find({spent:{$mod:[100,0]}}); //spent%100==0
{ "_id" : 4, "category" : "misc", "budget" : 500, "spent" : 300 }





$elemMatch (Projection)
The content of the array field made limited using this operator from the query result to contain only the
first element matching the element $elemMatch condition. It is mainly used in array of objects cases.
Example:
{
_id: 1,
zipcode: "63109",
students: [
    { name: "john", school: 102, age: 10 },
    { name: "jess", school: 102, age: 11 },
    { name: "jeff", school: 108, age: 15
    ]
}
{
_id: 2,
zipcode: "63110",
students: [ { name: "ajax", school: 100, age: 7 }, { name: "achilles", school: 100, age: 8 }, ]  }
{
_id: 3,
zipcode: "63109",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 }, ]}
{
_id: 4,
zipcode: "63109",
students: [
{ name: "barney", school: 102, age: 7 }, { name: "ruth", school: 102, age: 16 },]}
Query ::
db.schools.find( { zipcode: "63109" },
{ students: { $elemMatch: { school: 102 } } } )
db.schools.find( { zipcode: "63109" },
{ students: { $elemMatch: { school: 102, age: { $gt: 10} } } } )





$slice
It controls the number of values in an array that a query returns.
Syntax:
db.books.find( { field: value }, { array: {$slice: count } } );
Syntax:
Db.collection.find(
<query to fetch>,{array_field:{$slice:[number_element_skip,number_element_slice]}}
)
Example:
> db.books.find()
{ "_id" : ObjectId("6380f3e4697633314268a0d2"), "name" : "c++book", "page" : 250, "price" : [ 200, 150, 300, 500 ] }
{ "_id" : ObjectId("6380f49b697633314268a0d3"), "name" : "javabook", "page" : 450, "price" : [ 20, 1500, 350, 600 ] }
{ "_id" : ObjectId("6380f49b697633314268a0d4"), "name" : "aspcookbook", "page" : 850, "price" : [ 900, 250 ] }
{ "_id" : ObjectId("6380f49b697633314268a0d5"), "name" : "mathsbook", "page" : 1150, "price" : [ 200, 450, 300,
500, 900 ] }
> db.books.find({name:{$eq:'javabook'}},{price:{$slice:3}}){ "_id" : ObjectId("6380f49b697633314268a0d3"), "name" : "javabook", "page" : 450, "price" : [ 20, 1500, 350 ] }
> db.books.find({ name:{$eq:'mathsbook'} }, { price:{$slice:[2,2]}  }  )
{ "_id" : ObjectId("6380f49b697633314268a0d5"), "name" : "mathsbook", "page" : 1150, "price" : [ 300, 500 ] }







TEXT SEARCH:
db.collectionname.find({$text:{$search:”text to search”}});
> db.createCollection('subject');
{ "ok" : 1 }
> db.subject.insertMany([{_id:10,sub:'maths',desc:'it is a good subject'},{_id:11,sub:'history',desc:'it is a good
subject'},{_id:12,sub:'physics',desc:'it is a interesting subject'},{_id:13,sub:'biology',desc:'it is a good subject'}]);
{ "acknowledged" : true, "insertedIds" : [ 10, 11, 12, 13 ] }
> db.subject.find();
{ "_id" : 10, "sub" : "maths", "desc" : "it is a good subject" }
{ "_id" : 11, "sub" : "history", "desc" : "it is a good subject" }
{ "_id" : 12, "sub" : "physics", "desc" : "it is a interesting subject" }
{ "_id" : 13, "sub" : "biology", "desc" : "it is a good subject" }
> db.subject.createIndex({desc:"text"});
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : false,
"ok" : 1
}
> db.subject.find({$text:{$search:"good subject"}});
{ "_id" : 13, "sub" : "biology", "desc" : "it is a good subject" }{ "_id" : 11, "sub" : "history", "desc" : "it is a good subject" }
{ "_id" : 10, "sub" : "maths", "desc" : "it is a good subject" }
{ "_id" : 12, "sub" : "physics", "desc" : "it is a interesting subject" }
> db.subject.find({$text:{$search:"good"}});
{ "_id" : 13, "sub" : "biology", "desc" : "it is a good subject" }
{ "_id" : 11, "sub" : "history", "desc" : "it is a good subject" }
{ "_id" : 10, "sub" : "maths", "desc" : "it is a good subject" }





INDEX CREATE:
db.collectionname.createIndex({fieldname:”text”});


Field Operator (works with update ())
$set (update operator) ------- two methods to use


updateOne() , updateMany()
1. Create the laptop Collection:

db.laptops.insertMany([
    { brand: "Dell", model: "Inspiron 15", ram: 8, storage: 256, price: 600 },
    { brand: "HP", model: "Pavilion 14", ram: 8, storage: 512, price: 750 },
    { brand: "Apple", model: "MacBook Air", ram: 8, storage: 256, price: 999 },
    { brand: "Lenovo", model: "ThinkPad X1", ram: 16, storage: 512, price: 1200 },
    { brand: "Asus", model: "ZenBook 13", ram: 16, storage: 256, price: 800 }
])


2. Using updateOne() to Update a Single Document:
db.laptops.updateOne(
    { brand: "Dell", model: "Inspiron 15" },  // Filter
    { $set: { price: 650 } }                  // Update operation
)

3. Using updateMany() to Update Multiple Documents:
db.laptops.updateMany(
    { ram: 8 },                 // Filter
    { $set: { ram: 12 } }        // Update operation
)




Set Top-Level Fields
In MongoDB, setting top-level fields refers to directly modifying or creating fields at the root level of a document, as opposed to nested or subfields. This concept is fundamental when you're working with documents in MongoDB, especially when updating or inserting data.

Consider a MongoDB document in a collection like this:
{
    "_id": ObjectId("60f8c9a5d5d5e92b1f1a1b2c"),
    "name": "John Doe",
    "age": 30,
    "address": {
        "street": "123 Elm St",
        "city": "Somewhere",
        "zip": "12345"
    }
}


Top-Level Fields: "_id", "name", "age", and "address" are top-level fields. These fields exist directly on the document itself.
Nested Fields: "street", "city", and "zip" are fields nested within the "address" field.

For the document matching the criteria _id equal to 100, the following operation uses
the $set operator to update the value of the quantity field, details field, and
the tags field.

db.products.updateOne(
{ _id: 100 }, { $set{quantity: 500details: { model: "2600", make: "Fashionaires" },
tags: [ "coats", "outerwear", "clothing"}  )





$min (it will set the upper limit of the field)
It changes the value of the field to a specified value if the specified value is less than the
current value of the filed.
Syntax:
1. { $min: { <field1>: <value1>, ... } }
Example:
Suppose we have a laptops collection, and we want to ensure that the price of a laptop does not exceed $1000.

Now, we want to ensure that no laptop in our collection has a price greater than $1000.
db.laptops.updateMany(
    {},                      // Match all documents
    { $min: { price: 1000 } } // Set price to 1000 if it's greater than 1000
)
Using the $min operator, you can effectively cap the value of a field to ensure it does not exceed a specified limit.






$max (it will set the lower limit of the field)
The $max operator in MongoDB is used to update a field with a specified value if the specified value is greater than the current value of the field. Essentially, it sets a lower limit on the field, ensuring that the field value does not fall below a certain threshold. If the current value of the field is less than the specified value, $max will update the field to the specified value. Otherwise, it leaves the field unchanged.

Now, let's update the ram field so that all laptops have at least 16GB of RAM.

db.laptops.updateMany(
    {},                     // Match all documents
    { $max: { ram: 16 } }   // Set ram to 16 if it's less than 16
)

It changes the value of the field to a specified value if the specified value is greater than
the current value of the filed.
Syntax:
1. { $max: { <field1>: <value1>, ... } }
Example:
1. { _id: 0021, highprice: 800, lowprice: 200 }
2. db.books.update( { _id: 0021 }, { $max: { highprice: 950 } } )




$mul
The $mul operator in MongoDB is used in update operations to multiply the value of a field by a specified number. This can be useful when you need to scale the values of certain fields, such as prices, quantities, or other numerical data.

Let's say we have a laptops collection, and we want to increase the price of each laptop by 10%.

Now, let's update the price field by multiplying it by 1.1 to increase each laptop's price by 10%.
db.laptops.updateMany(
    {},                    // Match all documents
    { $mul: { price: 1.1 } } // Multiply the price by 1.1 (increases price by 10%)
)


To increase the price by 75%, use a multiplier of 1.75.
db.laptops.updateMany(
    {},                      // Match all documents in the collection
    { $mul: { price: 1.75 } } // Multiply the price by 1.75 (increases price by 75%)
)


Steps to Increase Price by 25% and Round to Two Decimal Places.
db.laptops.updateMany(
    {},
    [ { $set: { price: { $round: [{ $multiply: ["$price", 1.25] }, 2]  } } }  ]
)


To increase the price by 80%, use a multiplier of 1.80.
db.laptops.updateMany(
    {},                      // Match all documents in the collection
    { $mul: { price: 1.80 } } // Multiply the price by 1.80 (increases price by 80%)
)


It multiplies the value of a field by a number.
Syntax:
1. { $mul: { <field1>: <number1>, ... } }
Example:
> db.employee.update({id:10},{$mul:{age:5}}) // multiply age property value by 5 and
update
AD
1. db.books.update(
2. { _id: 1 },
3. { $mul: { price: NumberDecimal("180.25"), qty: 2 } }
4. )





$rename
The rename operator changes the name of a field.
Syntax:1. {$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }
Example:
You can use the $rename operator in an updateMany operation to rename the field for all documents.
db.laptops.updateMany(
    {}, // Match all documents
    { $rename: { "model": "model_name" } } // Rename the field
)

> db.employee.update({id:14},{$rename:{"loc":"city"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.employee.find()
{ "_id" : ObjectId("62e3ca59fd9c1e79507d6e5f"), "id" : 10, "name" : "rajesh", "loc" : "pune", "age" : 100 }
{ "_id" : ObjectId("62e3ce28fd9c1e79507d6e61"), "id" : 12, "name" : "rajat", "loc" : "dunlop", "age" : 15 }
{ "_id" : ObjectId("62e3ce28fd9c1e79507d6e62"), "id" : 13, "name" : "Avishek", "loc" : "gariahat", "age" : 22 }
{ "_id" : ObjectId("62e3dff4fd9c1e79507d6e63"), "id" : 14, "name" : "rajat", "age" : 25, "city" : "pune" }
{ "_id" : ObjectId("62e3dff4fd9c1e79507d6e64"), "id" : 13, "name" : "seema", "loc" : "pune", "age" : 22 }
>




MongoDB limit() Method
In MongoDB, limit() method is used to limit the fields of document that you want to show. Sometimes, you have a lot
of documents in collection of your database and have to retrieve only 1 or 2. In such case, limit() method is used.
The MongoDB limit() method is used with find() method.
It limits the number of document to show.
Syntax:
1. db.COLLECTION_NAME.find().limit(NUMBER)
Example: Limit with sort()
db.laptops.find().sort({ price: -1 }).limit(3)







MongoDB skip() method
In MongoDB, skip() method is used to skip the document. It is used with find() and limit() methods.
AD
Syntax
1. db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER) 




Sort with a Single Field Index
If an ascending or a descending index is on a single field, the sort operation on the field can be in
either direction.
Syntax: db.COLLECTION_NAME.find({}).sort({field_sort:1(Asc) or -1(Desc) })
For example, 
 db.laptops.find().sort({brand: 1}).skip(3).limit(3)

create an ascending index on the field a for a collection records:
db.records.createIndex( { a: 1 } )
This index can support an ascending sort on a:
db.records.find().sort( { a: 1 } )
The index can also support the following descending sort on a by traversing the index in reverse order:
db.records.find().sort( { a: -1 } )
Example:
> db.books.createIndex({name:1});
{
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"createdCollectionAutomatically" : false,
"ok" : 1
}
> db.books.find().sort({name:1})
{ "_id" : ObjectId("6380f49b697633314268a0d4"),
"name" : "aspcookbook", "page" : 850, "price" : [ 900, 250
] }
{ "_id" : ObjectId("6380f3e4697633314268a0d2"),
"name" : "c++book", "page" : 250, "price" : [ 200, 150,
300, 500 ] }
{ "_id" : ObjectId("6380f49b697633314268a0d3"),
"name" : "javabook", "page" : 450, "price" : [ 20, 1500,
350, 600 ] }
{ "_id" : ObjectId("6380f49b697633314268a0d5"),
"name" : "mathsbook", "page" : 1150, "price" : [ 200, 450,
300, 500, 900 ] }
> db.books.find().sort({name:-1})
{ "_id" : ObjectId("6380f49b697633314268a0d5"),
"name" : "mathsbook", "page" : 1150, "price" : [ 200, 450,
300, 500, 900 ] }
{ "_id" : ObjectId("6380f49b697633314268a0d3"),
"name" : "javabook", "page" : 450, "price" : [ 20, 1500,
350, 600 ] }
{ "_id" : ObjectId("6380f3e4697633314268a0d2"), "name" : "c++book", "page" : 250, "price" : [ 200, 150,
300, 500 ] }
{ "_id" : ObjectId("6380f49b697633314268a0d4"),
"name" : "aspcookbook", "page" : 850, "price" : [ 900, 250
] }
>



Sort with multi-fields :
Syntax :
Db.collectionname.find({}).sort({field_name:1 or -1 , field_name : 1 or -1 })



Count - runCommand 
To count the number of all the documents in the collection ‘orders’:
1. db.runCommand( { count: 'orders' } )






Aggregation Pipeline Operators ( using $project command :)
The aggregation pipeline operators construct expressions for use in the aggregation
pipeline stages.
Basic syntax:
db.collectionname.aggregate([ { $project: { field_nm: 1, projection_name: <query> } } ]);


Arithmetic Expression Operators
It is used to perform arithmetic operations on numbers. Some arithmetic expression also
supports data arithmetic.

$abs
The abs operator returns the absolute value of a number.
Syntax:
1. { $abs: <number> }
Example:> db.pipelineex.find();
{ "_id" : 1, "start" : 5, "end" : 8 }
{ "_id" : 2, "start" : 4, "end" : 4 }
{ "_id" : 3, "start" : 9, "end" : 7 }
{ "_id" : 4, "start" : 6, "end" : 7 }
> db.pipelineex.aggregate([
    {
     $project: { delta: { $abs: { $subtract: [ "$start", "$end" ] } } }
    }
]);
{ "_id" : 1, "delta" : 3 }
{ "_id" : 2, "delta" : 0 }
{ "_id" : 3, "delta" : 2 }
{ "_id" : 4, "delta" : 1 }



$add
It adds two or more numbers and a date. If one of the arguments is a date, then the
date treats the other argument as milliseconds to add to the date.
Syntax:
1. { $add: [ <expression1>, <expression2>, ... ] }
Example:
> db.pipelineex.aggregate([ { $project: { total: { $add: [ "$start", "$end" ] } } } ]);
{ "_id" : 1, "total" : 13 }
{ "_id" : 2, "total" : 8 }
{ "_id" : 3, "total" : 16 }
{ "_id" : 4, "total" : 13 }
> db.pipelineex.aggregate([ { $project: { diff: { $subtract: [ "$start", "$end" ] } } } ]);
{ "_id" : 1, "diff" : -3 }
{ "_id" : 2, "diff" : 0 }
{ "_id" : 3, "diff" : 2 }
{ "_id" : 4, "diff" : -1 }




$ceil
The ceil operator returns the smallest integer that is greater than or equal to the
specified number.
Syntax:
1. { $ceil: <number> }
Example:
1. db.samples.aggregate([ { $project: { value: 1, ceilingValue: { $ceil: "$value" } } } ])




$divide
It divides one or more numbers by another and returns the result.
Syntax:
1. { $divide: [ <expression1>, <expression2> ] }
Example:
db.books.aggregate([{ $project: { _id:0, title:1, pageDiv100: {$divide: ["$page", 100 ]} } }])
[
  { title: 'Book One', pageDiv100: 4.5 },
  { title: 'Book Two', pageDiv100: 3 },
  { title: 'Book Three', pageDiv100: 6 },
  { title: 'Book Four', pageDiv100: 2 }
]




$floor
The floor operator returns the greatest integer less than or equal to the specified
number.Syntax:
1. { $floor: <number> }
Example:
1. db.samples.aggregate( [ { $project: { value: 1, floorValue: { $floor: "$value" } } } ] )



$mod
The mod operator divides one number with another and returns the remainder. So, the $mod operator checks if the result of the division field % divisor equals the remainder.
Syntax:
1. { field: { $mod: [divisor, remainder] } }

Example:
1. db.planning.aggregate(
2. [
3. { $project: { remainder: { $mod: [ "$hours", "$tasks" ] } } }
4. ]
5. )





$multiply
The multiply operator gives the product of two or more numbers.
Syntax:
1. { $multiply: [ <expression1>, <expression2>, ..... ] }
Example:
1.
db.sales.aggregate( [ { $project: { date: 1, item: 1, total: { $multiply: [ "$price", "$quantity
" ] } } } ] )




$pow
The pow operator raises the number to the given exponent and returns the result. 2^3 = 8
Syntax:
1. { $pow: [ <number>, <exponent> ] }
Example:
1.
db.quizzes.aggregate( [ { $project: { variance: { $pow: [ { $stdDevPop: "$scores.score" },
2 ] } } } ] )




$round
The round operator rounds a number to a whole integer or a specified decimal place.
Syntax:
1. { $round : [ <number>, <place> ] }
Example:
1. db.samples.aggregate( [ { $project: { roundedValue: { $round: [ "$value", 1 ] } } } ] )




$sqrt
The sqrt operator returns the square root of a positive number as double.
Syntax:
1. { $sqrt: <number> }
Example:
1. db.points.aggregate([
2. {
3. $project: {
4. distance: {
5. $sqrt: {
6. $add: [ 7. { $pow: [ { $subtract: [ "$p2.y", "$p1.y" ] }, 2 ] },
8. { $pow: [ { $subtract: [ "$p2.x", "$p1.x" ] }, 2 ] }
9. ]
10. }
11. }
12. }
13. }
14.])




$subtract
The subtract operator subtracts two or more numbers to return the difference of the
number.
Syntax:
1. { $subtract: [ <expression1>, <expression2> ] }
Example:
1.
db.sales.aggregate( [ { $project: { item: 1, total: { $subtract: [ { $add: [ "$price", "$fee" ] },
"$discount" ] } } } ] )





$trunc
The trunc command deletes the data from the specified decimal place.
Syntax:
1. { $trunc : [ <number>, <place> ] }
Example:
1. db.samples.aggregate( [ { $project: { truncatedValue: { $trunc: [ "$value", 1 ] } } } ] )

Can We use array in arithmetic operator. => Yes.
 {
    _id: ObjectId('66a48811f5977479b71f3412'),
    title: 'Book Four',
    author: 'Author Four',
    page: 200,
    price: [ 5.99, 6.99, 7.99, 8.99 ]
  }

You can truncate each price in the price array to its integer part using the following aggregation pipeline:

db.books.aggregate([
  {
    $project: {
      _id: 0,
      title: 1,
      truncatedPrices: {
        $map: {
          input: "$price",
          as: "p",
          in: { $trunc: "$$p" }
        }
      }
    }
  }
])







Array Expression Operator

$arrayElemAt
it returns the element at the specified array index.
Syntax:
1. { $arrayElemAt: [ <array>, <idx> ] }
Example:
db.createCollection("emp");
db.emp.deleteMany({});
db.emp.drop();

 db.emp.insertMany([  { "name" : "Raj", "age" : 20, "loc" : "kolkata", "gen" :"male", "skills" : [ "c", "c++", "php" ] },   { "name" : "Seema", "age" : 18, "loc" : "kolkata", "gen" :"female", "skills" : [ "python", "php" ] }, { "name" : "Ravi", "age" : 20, "loc" : "kolkata", "gen" :"male", "skills" : [ "c#.net", "c++", "php" ] } ,  { "name" : "Suraj", "age" : 30, "loc" : "goa", "gen" : "male", "skills" : [ "react", "c++", "php", "java" ] }, { "name" : "Rita", "age" : 35, "loc" : "patna", "gen" : "female", "skills" : [ "react", "angular" ] }  ])

 db.emp.aggregate([ { $project:{ _id:0, bestSkill: {$arrayElemAt: ["$skills", 0] }  }  }])
[
  { bestSkill: 'c' },
  { bestSkill: 'c' },
  { bestSkill: 'python' },
  { bestSkill: 'c#.net' },
  { bestSkill: 'react' },
  { bestSkill: 'react' }
]
-1 for last index, -2 for second last index.





$arrayToObject
The arrayToObject operator converts an array into a single document.
Converts an array into a single document; the array must be either:
An array of two-element arrays where the first element is the field name, and the
second element is the field value:
[ [ [ "item", "abc123" ], [ "qty", 25 ] ] ]
- OR -
An array of documents that contains two fields, k and v where:
o The k field contains the field name.
o The v field contains the value of the field.
[ [ { "k": "item", "v": "abc123" }, { "k": "qty", "v": 25 } ] ]
Example:
Converting an Array of Key-Value Pairs
{
  "_id": 1,
  "item": "Notebook",
  "keyValuePairs": [
    { "k": "brand", "v": "XYZ" },
    { "k": "price", "v": 20 },
    { "k": "color", "v": "black" }
  ]
}

You can use $arrayToObject to convert the keyValuePairs array into a standard object:
db.products.aggregate([
  {
    $project: {
      _id: 0,
      item: 1,
      attributes: { $arrayToObject: "$keyValuePairs" }
    }
  }
])

Output:
{
  "item": "Notebook",
  "attributes": {
    "brand": "XYZ",
    "price": 20,
    "color": "black"
  }
}






$concatArrays
The concatArrays operator joins the array to return the concatenated array.
Syntax:
1. { $concatArrays: [ <array1>, <array2>, ... ] }
Example:
> db.concatarray.find();
{ "_id" : 1, "name" : "raj", "skills" : [ "java", "c", "c++" ], "dept" : [ "maths", "history" ] }
{ "_id" : 2, "name" : "rajat", "skills" : [ "python", "c#.net", "c++" ], "dept" : [ "maths", "biology" ] }
{ "_id" : 3, "name" : "seema", "skills" : [ "java", "php" ], "dept" : [ "maths", "physics" ] }
> db.concatarray.aggregate([{$project:{concatval:{$concatArrays:["$skills","$dept"] }}}]);
{ "_id" : 1, "concatval" : [ "java", "c", "c++", "maths", "history" ] }
{ "_id" : 2, "concatval" : [ "python", "c#.net", "c++", "maths", "biology" ] }
{ "_id" : 3, "concatval" : [ "java", "php", "maths", "physics" ] }
>






$in
The in operator returns a Boolean indicating that the specified value is in the array or
not.
Syntax:
1. { $in: [ <expression>, <array expression> ] }
Example:
> db.stockinfo.find();
{ "_id" : 1, "location" : "24th Street", "in_stock" : [ "apples", "oranges", "bananas" ] }
{ "_id" : 2, "location" : "36th Street", "in_stock" : [ "bananas", "pears", "grapes" ] }
{ "_id" : 3, "location" : "82nd Street", "in_stock" : [ "cantaloupes", "watermelons", "apples" ] }
>db.stockinfo.aggregate([{$project:{"store_name":"$location","apple_stock":{$in:["apples","$in_s
tock"]}} }]);
{ "_id" : 1, "store_name" : "24th Street", "apple_stock" : true }{ "_id" : 2, "store_name" : "36th Street", "apple_stock" : false }
{ "_id" : 3, "store_name" : "82nd Street", "apple_stock" : true }
>




$indexOfArray
The indexOfArray operator searches the array for the occurrence of a specified value
and returns the array index of the first occurrence.
Syntax:
1. { $indexOfArray: [ <array expression>, <search expression>, <start>, <end> ] }
<start> <end> optional index
<start> by default 0 <end> by default end of string
Example:
> db.stockinfo.find();
{ "_id" : 1, "location" : "24th Street", "in_stock" : [ "apples", "oranges", "bananas" ] }
{ "_id" : 2, "location" : "36th Street", "in_stock" : [ "bananas", "pears", "grapes" ] }
{ "_id" : 3, "location" : "82nd Street", "in_stock" : [ "cantaloupes", "watermelons", "apples" ] }
> db.stockinfo.aggregate([{$project:{pos:{$indexOfArray:["$in_stock","bananas"]}}}]);
{ "_id" : 1, "pos" : 2 }
{ "_id" : 2, "pos" : 0 }
{ "_id" : 3, "pos" : -1 }





$range
The range operator returns an array whose elements are a generated sequence of
numbers. $range generates the sequence from the specified starting number by successively
incrementing the starting number by the specified step value up to but not including the end
point.
Syntax:1. { $range: [ <start>, <end>, <non-zero step> ] }
Example:
> db.distanceinfo.find();
{ "_id" : 0, "city" : "San Jose", "distance" : 42 }
{ "_id" : 1, "city" : "Sacramento", "distance" : 88 }
{ "_id" : 2, "city" : "Reno", "distance" : 218 }
{ "_id" : 3, "city" : "Los Angeles", "distance" : 383 }
>
db.distanceinfo.aggregate([{$project:{"city":"$city","dist_stopage":{$range:[10,"$distance",30]}}}]
);
{ "_id" : 0, "city" : "San Jose", "dist_stopage" : [ 10, 40 ] }
{ "_id" : 1, "city" : "Sacramento", "dist_stopage" : [ 10, 40, 70 ] }
{ "_id" : 2, "city" : "Reno", "dist_stopage" : [ 10, 40, 70, 100, 130, 160, 190 ] }
{ "_id" : 3, "city" : "Los Angeles", "dist_stopage" : [ 10, 40, 70, 100, 130, 160, 190, 220, 250, 280, 310,
340, 370 ] }






$reverseArray
It returns an array with the element in reverse order.
Syntax:
1. { $reverseArray: <array expression> }
Example:
> db.stockinfo.find()
{ "_id" : 1, "location" : "24th Street", "in_stock" : [ "apples", "oranges", "bananas" ] }
{ "_id" : 2, "location" : "36th Street", "in_stock" : [ "bananas", "pears", "grapes" ] }
{ "_id" : 3, "location" : "82nd Street", "in_stock" : [ "cantaloupes", "watermelons", "apples" ] }
> db.stockinfo.aggregate([{$project:{"reverse":{$reverseArray:"$in_stock"}}}]);
{ "_id" : 1, "reverse" : [ "bananas", "oranges", "apples" ] }
{ "_id" : 2, "reverse" : [ "grapes", "pears", "bananas" ] }
{ "_id" : 3, "reverse" : [ "apples", "watermelons", "cantaloupes" ] }
>






$size (in Aggregation pipeline)
The size operator counts and returns the total number of items in an array.
Syntax:
1. { $size: <expression> }
Example:
> db.stockinfo.aggregate([{$project:{"total":{$size:"$in_stock"}}}]);
{ "_id" : 1, "total" : 3 }
{ "_id" : 2, "total" : 3 }
{ "_id" : 3, "total" : 3 }





$slice (in Aggregation pipeline)
The slice operator results in a subset of an array.
Example ::
> db.favorite.find();
{ "_id" : 1, "name" : "dave123", "favorites" : [ "chocolate", "cake", "butter", "apples" ] }
{ "_id" : 2, "name" : "li", "favorites" : [ "apples", "pudding", "pie" ] }
{ "_id" : 3, "name" : "ahn", "favorites" : [ "pears", "pecans", "chocolate", "cherries" ] }
{ "_id" : 4, "name" : "ty", "favorites" : [ "ice cream" ] }
> db.favorite.aggregate([{$project:{"name":"$name","food":{$slice:["$favorites",2]}}}]);
{ "_id" : 1, "name" : "dave123", "food" : [ "chocolate", "cake" ] }
{ "_id" : 2, "name" : "li", "food" : [ "apples", "pudding" ] }{ "_id" : 3, "name" : "ahn", "food" : [ "pears", "pecans" ] }
{ "_id" : 4, "name" : "ty", "food" : [ "ice cream" ] }
> db.favorite.aggregate([{$project:{"name":"$name","food":{$slice:["$favorites",-2]}}}]);
{ "_id" : 1, "name" : "dave123", "food" : [ "butter", "apples" ] }
{ "_id" : 2, "name" : "li", "food" : [ "pudding", "pie" ] }
{ "_id" : 3, "name" : "ahn", "food" : [ "chocolate", "cherries" ] }
{ "_id" : 4, "name" : "ty", "food" : [ "ice cream" ] }
> db.favorite.aggregate([{$project:{"name":"$name","food":{$slice:["$favorites",1,2]}}}]);
{ "_id" : 1, "name" : "dave123", "food" : [ "cake", "butter" ] }
{ "_id" : 2, "name" : "li", "food" : [ "pudding", "pie" ] }
{ "_id" : 3, "name" : "ahn", "food" : [ "pecans", "chocolate" ] }
{ "_id" : 4, "name" : "ty", "food" : [ ] }
>





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 following example returns different values for the field books from all documents in
the library collection:
Syntax :
db.runCommand ( { distinct: "collection_nm", key: "field_nm" } )
1. db.runCommand ( { distinct: "library", key: "books" } )
example :
> db.testing.find({});
{ "_id" : ObjectId("649fcb2dc17bc4392a1ea136"), "name" : "raj", "loc" : "pune" }
{ "_id" : ObjectId("649fcb2dc17bc4392a1ea137"), "name" : "Rajat", "loc" : "pune" }
{ "_id" : ObjectId("649fcb2dc17bc4392a1ea138"), "name" : "Ravi", "loc" : "kolkata" }{ "_id" : ObjectId("649fcb2dc17bc4392a1ea139"), "name" : "Seema", "loc" : "pune" }
{ "_id" : ObjectId("649fcb2dc17bc4392a1ea13a"), "name" : "Raja", "loc" : "kolkata" }
>
> db.runCommand({distinct:"testing",key:"loc"});
{ "values" : [ "kolkata", "pune" ], "ok" : 1 }
>





How to Join Two Collections in Mongo DB
We can join documents on collections in MongoDB by using the $lookup (Aggregation) function. 

$lookup
(Aggregation) creates an outer left join with another collection and helps to filter data from merged data.
Syntax
In MongoDB’s JOIN operation, the goal is to connect one set of data to another set of data. To join two collections, we use the $lookup operator, whose syntax is defined below:
{
$lookup
{
from: <collection to join>,
LocalField: <field from the input documents>,
Foreign Field: <field from the documents of the "from" collection>,
As: <output array field>
}
}
The $lookup function accepts a document containing these fields:
From: It describes the collection within an identical database that should be used for executing the join, but with sharded
collection restrictions.
LocalField: This field represents the input field from the documents to the stage of $lookup, which performs an
equivalence match between the local-field and the foreign-field from the collection ‘from.’ If an input document does not
have a value for a local-field, then this operator will give the field a null value for matching purposes.
Foreign Field: This field contains data from the documents in the ‘from’ collection with which an equivalence match can
be made between the foreignField and the localField. When a document in the collection ‘from’ does not have a
foreignField value, this operator will set the field to null for further matching purposes.
As: It specifies the name of the array field that needs to be added to the input documents. More so, a new array field also
includes matching documents from the collection ‘from.’ The prevailing field will be overwritten if the stated name already
exists in the input document.

Step 1: Create the furniture Collection
Let's insert some documents into the furniture collection:

db.furniture.insertMany([
  { _id: 1, item: "Chair", price: 50, category: "Seating" },
  { _id: 2, item: "Desk", price: 150, category: "Tables" },
  { _id: 3, item: "Couch", price: 300, category: "Seating" },
  { _id: 4, item: "Shelf", price: 100, category: "Storage" }
])

Step 2: Create the office Collection
db.office.insertMany([
  { _id: 1, furniture_id: 1, room: "Conference Room", quantity: 10 },
  { _id: 2, furniture_id: 2, room: "Executive Office", quantity: 5 },
  { _id: 3, furniture_id: 3, room: "Lobby", quantity: 2 },
  { _id: 4, furniture_id: 4, room: "Storage Room", quantity: 20 }
])


Step 3: Perform an Aggregation with $lookup
db.furniture.aggregate([
  {
    $lookup: {
      from: "office", // The collection to join
      localField: "_id", // The field from the 'furniture' collection
      foreignField: "furniture_id", // The field from the 'office' collection
      as: "officeDetails" // The name of the array field to add the joined data
    }
  },
  {
    $project: {
      _id: 0,
      item: 1,
      price: 1,
      officeDetails: 1
    }
  }
])

-------------------------------------------------------------------x-----------------------------------------------------x----------------------------------------------------------------
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------x-----------------------------------------------------x----------------------------------------------------------------

To cover all the operators and methods you listed, let's create a `testCollection` with a sample document, then apply various MongoDB queries. I'll walk you through the creation of the document and the queries step-by-step.

Step 1: Create a Sample Document
Let's insert a sample document into a collection named `testCollection`:

db.testCollection.insertOne({
  name: "Example Document",
  category: "test",
  price: 250.75,
  stock: 30,
  tags: ["electronics", "sale", "popular"],
  dimensions: { length: 20, width: 15, height: 5 },
  lastUpdated: new Date(),
  ratings: [5, 4, 3],
  discount: { type: "percentage", value: 10 },
  reviews: [
    { user: "Alice", comment: "Great product", rating: 5 },
    { user: "Bob", comment: "Good value", rating: 4 }
  ]
})
db.testCollection.insertMany([
  {
    name: "Gadget A",
    category: "electronics",
    price: 150.99,
    stock: 100,
    tags: ["gadgets", "sale"],
    dimensions: { length: 10, width: 5, height: 2 },
    lastUpdated: new Date("2024-01-15"),
    ratings: [5, 3, 4],
    discount: { type: "fixed", value: 20 },
    reviews: [
      { user: "Charlie", comment: "Worth the price", rating: 5 },
      { user: "Dave", comment: "Average", rating: 3 }
    ]
  },
  {
    name: "Book B",
    category: "books",
    price: 25.75,
    stock: 50,
    tags: ["books", "popular"],
    dimensions: { length: 8, width: 6, height: 1 },
    lastUpdated: new Date("2024-01-10"),
    ratings: [4, 4, 5],
    discount: { type: "percentage", value: 5 },
    reviews: [
      { user: "Emma", comment: "Interesting read", rating: 4 },
      { user: "Frank", comment: "Highly recommend", rating: 5 }
    ]
  },
  {
    name: "Furniture C",
    category: "furniture",
    price: 500.00,
    stock: 10,
    tags: ["furniture", "new"],
    dimensions: { length: 60, width: 30, height: 40 },
    lastUpdated: new Date("2024-01-05"),
    ratings: [3, 4],
    discount: { type: "fixed", value: 50 },
    reviews: [
      { user: "Grace", comment: "Good quality", rating: 4 },
      { user: "Henry", comment: "Expensive but good", rating: 3 }
    ]
  }
])



Step 2: Queries for Operators and Methods

Comparison Operators

// $eq
db.testCollection.find({ price: { $eq: 250.75 } })

// $ne
db.testCollection.find({ stock: { $ne: 50 } })

// $gt
db.testCollection.find({ stock: { $gt: 20 } })

// $gte
db.testCollection.find({ price: { $gte: 250 } })

// $in
db.testCollection.find({ tags: { $in: ["sale", "discount"] } })

// $lt
db.testCollection.find({ stock: { $lt: 50 } })

// $lte
db.testCollection.find({ price: { $lte: 300 } })

// $nin
db.testCollection.find({ tags: { $nin: ["new", "limited"] } })


     Logical Operators

// $and
db.testCollection.find({ $and: [ { price: { $gt: 200 } }, { stock: { $gt: 20 } } ] })

// $or
db.testCollection.find({ $or: [ { price: { $lt: 100 } }, { stock: { $lt: 10 } } ] })

// $not
db.testCollection.find({ price: { $not: { $gt: 300 } } })

// $nor
db.testCollection.find({ $nor: [ { price: { $gt: 300 } }, { stock: { $lt: 10 } } ] })


 Element Operators

// $exists
db.testCollection.find({ discount: { $exists: true } })

// $all
db.testCollection.find({ tags: { $all: ["electronics", "popular"] } })

// $elemMatch
db.testCollection.find({ reviews: { $elemMatch: { rating: 5, user: "Alice" } } })

// $size
db.testCollection.find({ tags: { $size: 3 } })


 Evaluation Operators

// $expr
db.testCollection.find({ $expr: { $gt: [ "$price", 200 ] } })

// $mod
db.testCollection.find({ stock: { $mod: [5, 0] } })

// $elemMatch (inside an array field)
db.testCollection.find({ reviews: { $elemMatch: { rating: 4 } } })

// $slice
db.testCollection.find({}, { reviews: { $slice: 1 }, tags: { $slice: -2 } })

// $text: $search (first create text index on the `tags` field)
db.testCollection.createIndex({ tags: "text" })
db.testCollection.find({ $text: { $search: "sale" } })


Set Top-Level Field Operators

// $min (set the minimum price if it's lower than current)
db.testCollection.updateOne({ _id: ObjectId("...") }, { $min: { price: 200 } })

// $max (set the maximum stock if it's higher than current)
db.testCollection.updateOne({ _id: ObjectId("...") }, { $max: { stock: 50 } })

// $mul (multiply price by 1.10, effectively increasing by 10%)
db.testCollection.updateOne({ _id: ObjectId("...") }, { $mul: { price: 1.10 } })

// $round (round price to 2 decimal places)
db.testCollection.updateOne({ _id: ObjectId("...") }, { $round: { price: 2 } })

// $multiply (multiply price by 2)
db.testCollection.updateOne({ _id: ObjectId("...") }, { $mul: { price: 2 } })

// $rename (rename the field `category` to `type`)
db.testCollection.updateOne({ _id: ObjectId("...") }, { $rename: { category: "type" } })


 Query Modifiers and Other Operations

// updateOne
db.testCollection.updateOne({ name: "Example Document" }, { $set: { stock: 25 } })

// updateMany
db.testCollection.updateMany({ price: { $gt: 100 } }, { $set: { status: "active" } })

// limit
db.testCollection.find().limit(2)

// skip
db.testCollection.find().skip(2)

// sort
db.testCollection.find().sort({ price: 1 })

// find
db.testCollection.find({ name: "Example Document" })

// runCommand
db.runCommand({ distinct: "testCollection", key: "category" })

// createCommand (a custom command)
db.runCommand({ create: "newCollection" })

// deleteOne
db.testCollection.deleteOne({ name: "Example Document" })

// deleteMany
db.testCollection.deleteMany({ stock: { $lt: 50 } })

// drop
db.testCollection.drop()

// insertOne
db.testCollection.insertOne({ name: "New Item", price: 120 })

// insertMany
db.testCollection.insertMany([
  { name: "Item A", price: 100 },
  { name: "Item B", price: 200 }
])

// aggregate (simple example)
db.testCollection.aggregate([
  { $match: { price: { $gt: 100 } } },
  { $group: { _id: "$category", total: { $sum: "$price" } } }
])


 Aggregation Pipeline Operators

// $abs (absolute value)
db.testCollection.aggregate([{ $project: { absPrice: { $abs: "$price" } } }])

// $add (add values)
db.testCollection.aggregate([{ $project: { totalStockValue: { $add: ["$price", "$stock"] } } }])

// $subtract (subtract values)
db.testCollection.aggregate([{ $project: { priceDiff: { $subtract: ["$price", 100] } } }])

// $multiply
db.testCollection.aggregate([{ $project: { totalPrice: { $multiply: ["$price", 1.2] } } }])

// $divide
db.testCollection.aggregate([{ $project: { halfPrice: { $divide: ["$price", 2] } } }])

// $ceil (ceiling of price)
db.testCollection.aggregate([{ $project: { ceilPrice: { $ceil: "$price" } } }])

// $floor (floor of price)
db.testCollection.aggregate([{ $project: { floorPrice: { $floor: "$price" } } }])

// $mod (modulus)
db.testCollection.aggregate([{ $project: { modStock: { $mod: ["$stock", 5] } } }])

// $pow (power)
db.testCollection.aggregate([{ $project: { powPrice: { $pow: ["$price", 2] } } }])

// $round (round price)
db.testCollection.aggregate([{ $project: { roundPrice: { $round: ["$price", 1] } } }])

// $sqrt (square root)
db.testCollection.aggregate([{ $project: { sqrtPrice: { $sqrt: "$price" } } }])

// $trunc (truncate to decimal places)
db.testCollection.aggregate([{ $project: { truncPrice: { $trunc: ["$price", 1] } } }])

// $arrayElemAt (get element from array)
db.testCollection.aggregate([{ $project: { firstTag: { $arrayElemAt: ["$tags", 0] } } }])

// $arrayToObject (convert array to object)
db.testCollection.aggregate([{ $project: { tagsObj: { $arrayToObject: "$tags" } } }])

// $concatArrays (concatenate arrays)
db.testCollection.aggregate([{ $project: { combinedTags: { $concatArrays: ["$tags", ["new"]] } } }])

// $in (check if value in array)
db.testCollection.aggregate([{ $match: { $expr: { $in: ["$category", ["test", "sale"]] } } }])

// $indexOfArray (find index of element in array)
db.testCollection.aggregate([{ $project: { indexInTags: { $indexOfArray: ["$tags", "sale"] } } }])

// $range (create array of numbers)
db.testCollection.aggregate([{ $project: { numberRange: { $range: [0, 10, 2] } } }])

// $reverseArray (reverse an array)
db.testCollection.aggregate([{ $project: { reversedTags: { $reverseArray: "$tags" } } }])

// $size (size of array)
db.testCollection.aggregate([{ $project: { tagCount: { $size: "$tags" } } }])

// $slice (slice an array)
db.testCollection.aggregate([{ $project: { firstTwoTags: { $slice: ["$tags", 0, 2] } } }])


 Output:
These queries will return documents or perform operations based on the conditions and pipeline stages defined. You can execute these queries in your MongoDB environment to see the actual outputs.


Comments