Show Database

test> show dbsOr
test> show databases
OUTPUT: user-managment 212.00 KiB
 admin 304.00 KiB
 local 25.91 GiB

Create Database

test> use <database_name>
Example : 
test>use ekartOUTPUT:
switched to db ekart

Create Collections

Example 1 : 
ekart> db.createCollection("shop_details")OUTPUT:
 { ok: 1 }

Example 2 : Create collection and insert the document at the same time
ekart> db.brand_details.insertOne(
 {name:"apple",
 head_office:"USA",
 products:["mobile","laptop","tv","head phone"],
 address:{
 building:"apple company",
 road:"apple company road",
 city:"new york",
 country:"USA",
 pincode:678899
 }
 })


OUTPUT:
{
  acknowledged: true,
  insertedId: ObjectId("66957f03223aa65aed2ad196")
}

Show Collections

ekart> show collections
OUTPUT:
 brand_details
 orders
 products
 shop_details
 shops
 users

add validation while creating collection

  • Create a collection with name “retailers” with below validations
    • required fields in collections are name, licensed and owner
    • each attribute has its defined data type like string,number,bool,object and array
    • similarly attribute with array (“locations”) will contains “items” associated properties
    • attribute with object(“owner”) values again contains the required, properties like above
ekart> db.createCollection("retailers", {
   validator: {
     $jsonSchema: {
       required: ["name", "licensed","owner"],
       properties: {
         name: {
           bsonType: "string",
           description: "name of the retailer",
         },
         licensed: {
           bsonType: "bool",
           description: " is retailed has valid license",
         },
         locations: {
           bsonType: "array",
           description: "availale locations of retailer",
           items: {
             bsonType: "string",
             description: "location name of retailer shop",
           },
         },
         owner: {
           bsonType: "object",
           description: "Retailer owner address details",
           required: ["name", "income"],
           properties: {
             name: {
               bsonType: "string",
               description: "owner name must be required",
             },
             state: {
               bsonType: "string",
               description: "owner resident state must be required",
             },
             income: {
               bsonType: "number",
               description: "owner income must be required",
             },
           },
         },
       },
     },
   },
   validationAction: "error",
 });

OUTPUT:
{ ok: 1 }

view collection/schema definitions

ekart> db.getCollectionInfos({name:"retailers"})

OUTPUT:
[
  {
    name: 'retailers',
    type: 'collection',
    options: {
      validator: {
        '$jsonSchema': {
          required: [ 'name', 'licensed' ],
          properties: {
            name: { bsonType: 'string', description: 'name of the retailer' },
            licensed: {
              bsonType: 'bool',
              description: ' is retailed has valid license'
            },
            locations: {
              bsonType: 'array',
              description: 'availale locations of retailer',
              items: [Object]
            },
            owner: {
              bsonType: 'object',
              description: 'Retailer owner address details',
              required: [Array],
              properties: [Object]
            }
          }
        }
      },
      validationAction: 'error'
    },
    info: {
      readOnly: false,
      uuid: new UUID("33ed4277-9dd6-4ade-bca5-ba3f6b1c9f86")
    },
    idIndex: { v: 2, key: { _id: 1 }, name: '_id_' }
  }
]

Error sample when validation is failed

Explaination: when inserting a new document to retailers collection “owners” details are missed which are defined as required while creating collection or schema(Above example)

ekart> db.retailers.insertOne({
     name: "ekart",
     licensed: true,
     locations: ["bangalore", "mumbai", "goa"],
     owner: {
     },
   });


OUTPUT:
Uncaught:
MongoServerError: Document failed validation
Additional information: {
  failingDocumentId: ObjectId("66965c05223aa65aed2ad1af"),
  details: {
    operatorName: '$jsonSchema',
    schemaRulesNotSatisfied: [
      {
        operatorName: 'properties',
        propertiesNotSatisfied: [
          {
            propertyName: 'owner',
            description: 'Retailer owner address details',
            details: [
              {
                operatorName: 'required',
                specifiedAs: { required: [ 'name', 'income' ] },
                missingProperties: [ 'income', 'name' ]
              }
            ]
          }
        ]
      }
    ]
  }
}

update schema definitions or validations

updating the location from array to string and updated state as required in owner nested object

  • db.runCommand() –
  • collMod –
ekart> db.runCommand(
    {
        collMod:"retailers",
        validator: {
            $jsonSchema: {
              required: ["name", "licensed"],
              properties: {
                name: {
                  bsonType: "string",
                  description: "name of the retailer",
                },
                licensed: {
                  bsonType: "bool",
                  description: " is retailed has valid license",
                },
                location: {
                  bsonType: "string",
                  description: "availale locations of retailer",
                },
                owner: {
                  bsonType: "object",
                  description: "Retailer owner address details",
                  required: ["name", "income","state"],
                  properties: {
                    name: {
                      bsonType: "string",
                      description: "owner name must be required",
                    },
                    state: {
                      bsonType: "string",
                      description: "owner resident state must be required",
                    },
                    income: {
                      bsonType: "number",
                      description: "owner income must be required",
                    },
                  },
                },
              },
            },
          },
          validationAction:'error'
    }
  )

OUTPUT:
{
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp({ t: 1721132783, i: 14 }),
    signature: {
      hash: Binary.createFromBase64("dlA6FZS9f8nkfa+FWSDvveK0LG0=", 0),
      keyId: Long("7351807554785116165")
    }
  },
  operationTime: Timestamp({ t: 1721132783, i: 14 })
}

drop collection(delete)

ekart> db.shops.drop()

OUTPUT:
true

Create/Add/Insert One document

ekart> db.brand_details.insertOne( 
{ 
name: "nikon", 
head_office: "china", 
products: ["DSLR Camera"], 
address: 
{ 
building: "nikon company", 
road: "nikon company road", 
city: "ching cho", 
country: "china", 
pincode: 909090 
} 
}
)

OUTPUT:
{
  acknowledged: true,
  insertedId: ObjectId("6695835f223aa65aed2ad199")
}

Create/Add/Insert multiple document

ekart> db.brand_details.insertMany([ 
{name:"samsung",
head_office:"korea",
products:["mobile",
"laptop","tv","smart watches"],
address:
{
building:"samsung",
road:"samsung road",
city:"some city",
country:"korea",
pincode:456677
}
},
{name:"nokia",
head_office:"japan",
products:["mobile"],
address:
{
building:"nokia",
road:"nokia road",
city:"some city",
country:"japan",
pincode:6766767
}
}
])

OUTPUT:
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId("669581b1223aa65aed2ad197"),
    '1': ObjectId("669581b1223aa65aed2ad198")
  }
}

Options in InsertMany()

syntax insertMany(data,options).Even we get the error in first document insertion due to duplicate “id” ,by ignoring the first document error ,remaining document are got inserted due the options that we provide as second parameter i.e {ordered:false}

ekart> db.brand_details.insertMany([
  {
    _id: ObjectId("6695835f223aa65aed2ad199"),
    name: 'nikon',
    head_office: 'germany',
    products: [ 'DSLR Camera', 'Mirrorless camera' ],
    address: {
      building: 'nikon company',
      road: 'nikon company road',
      city: 'ching cho',
      country: 'germany',
      pincode: 909090
    },
    founder: 'john deo'
  },
  {
    name: 'sony',
    head_office: 'japan',
    products: [ 'Mirrorless camera', 'PlayStation' ],
    address: {
      building: 'sony company',
      road: 'sony company road',
      city: 'tokyo',
      country: 'japan',
      pincode: 101010
    },
    founder: 'akira yamamoto'
  },
  {
    name: 'apple',
    head_office: 'usa',
    products: [ 'iPhone', 'MacBook' ],
    address: {
      building: 'apple company',
      road: 'apple company road',
      city: 'cupertino',
      country: 'usa',
      pincode: 95014
    },
    founder: 'steve jobs'
  }
],{ordered:false});

OUTPUT:
Uncaught:
MongoBulkWriteError: E11000 duplicate key error collection: ekart.brand_details index: _id_ dup key: { _id: ObjectId('6695835f223aa65aed2ad199') }
Result: BulkWriteResult {
  insertedCount: 2,
  matchedCount: 0,
  modifiedCount: 0,
  deletedCount: 0,
  upsertedCount: 0,
  upsertedIds: {},
  insertedIds: {
    '0': ObjectId("6695835f223aa65aed2ad199"),
    '1': ObjectId("66963288223aa65aed2ad1ad"),
    '2': ObjectId("66963288223aa65aed2ad1ae")
  }
}
Write Errors: [
  WriteError {
    err: {
      index: 0,
      code: 11000,
      errmsg: "E11000 duplicate key error collection: ekart.brand_details index: _id_ dup key: { _id: ObjectId('6695835f223aa65aed2ad199') }",
      errInfo: undefined,
      op: {
        _id: ObjectId("6695835f223aa65aed2ad199"),
        name: 'nikon',
        head_office: 'germany',
        products: [ 'DSLR Camera', 'Mirrorless camera' ],
        address: {
          building: 'nikon company',
          road: 'nikon company road',
          city: 'ching cho',
          country: 'germany',
          pincode: 909090
        },
        founder: 'john deo'
      }
    }
  }
]

find documnet(one document)

  • Purpose: Retrieves a single document from a collection that matches a given query.
  • Returns: The first document that matches the query criteria.
  • Usage: Useful when you need only one document or want to check if a document exists.
ekart> db.brand_details.findOne()

OUTPUT:
{
  _id: ObjectId("66957f03223aa65aed2ad196"),
  name: 'apple',
  head_office: 'USA',
  products: [ 'mobile', 'laptop', 'tv', 'head phone' ],
  address: {
    building: 'apple company',
    road: 'apple company road',
    city: 'new york',
    country: 'USA',
    pincode: 678899
  }
}

find documents

  • Purpose: Retrieves multiple documents from a collection that match a given query.
  • Returns: A cursor to the documents that match the query criteria.(if there are more records the we will see Type “it” for more at the end out output(nothing but the cursor).
  • Usage: Useful when you want to retrieve all documents that satisfy the query conditions.
ekart> db.brand_details.find()

OUTPUT:
[
  {
    _id: ObjectId("66957f03223aa65aed2ad196"),
    name: 'apple',
    head_office: 'USA',
    products: [ 'mobile', 'laptop', 'tv', 'head phone' ],
    address: {
      building: 'apple company',
      road: 'apple company road',
      city: 'new york',
      country: 'USA',
      pincode: 678899
    }
  },
  {
    _id: ObjectId("669581b1223aa65aed2ad197"),
    name: 'samsung',
    head_office: 'korea',
    products: [ 'mobile', 'laptop', 'tv', 'smart watches' ],
    address: {
      building: 'samsung',
      road: 'samsung road',
      city: 'some city',
      country: 'korea',
      pincode: 456677
    }
  },
  ...
]
Type "it" for more

find documents by condition

(Example where name= nokia)

ekart> db.brand_details.find(
 {name:"nokia"}
 )

OUTPUT:
[
  {
    _id: ObjectId("669581b1223aa65aed2ad198"),
    name: 'nokia',
    head_office: 'japan',
    products: [ 'mobile' ],
    address: {
      building: 'nokia',
      road: 'nokia road',
      city: 'some city',
      country: 'japan',
      pincode: 6766767
    }
  }
]

(Example with $and with using nested object value)

ekart> db.brand_details.find( {$and:[{name:"nokia"},{'address.pincode':6766767}]}
)

OUTPUT:
[
  {
    _id: ObjectId("669581b1223aa65aed2ad198"),
    name: 'nokia',
    head_office: 'japan',
    products: [ 'mobile' ],
    address: {
      building: 'nokia',
      road: 'nokia road',
      city: 'some city',
      country: 'japan',
      pincode: 6766767
    }
  }
]

Example with $or and use array values

ekart> db.brand_details.find( { $or:[{products: "tv"},{products:"smart watches"}]})

OUTPUT:
[
  {
    _id: ObjectId("66957f03223aa65aed2ad196"),
    name: 'apple',
    head_office: 'USA',
    products: [ 'mobile', 'laptop', 'tv', 'head phone' ],
    address: {
      building: 'apple company',
      road: 'apple company road',
      city: 'new york',
      country: 'USA',
      pincode: 678899
    }
  },
  {
    _id: ObjectId("669581b1223aa65aed2ad197"),
    name: 'samsung',
    head_office: 'korea',
    products: [ 'mobile', 'laptop', 'tv', 'smart watches' ],
    address: {
      building: 'samsung',
      road: 'samsung road',
      city: 'some city',
      country: 'korea',
      pincode: 456677
    }
  }
]

Get the number of document in a collection

ekart> db.brand_details.find().count()

OUTPUT:
4

Loop and print all the documents in Json

ekart> db.brand_details.find().forEach((x)=>{printjson("Brand : ",x)})

OUTPUT:
Brand :  {
  _id: ObjectId("66957f03223aa65aed2ad196"),
  name: 'apple',
  head_office: 'USA',
  products: [
    'mobile',
    'laptop',
    'tv',
    'head phone'
  ],
  address: {
    building: 'apple company',
    road: 'apple company road',
    city: 'new york',
    country: 'USA',
    pincode: 678899
  }
}
Brand :  {
  _id: ObjectId("669581b1223aa65aed2ad197"),
  name: 'samsung',
  head_office: 'korea',
  products: [
    'mobile',
    'laptop',
    'tv',
    'smart watches'
  ],
  address: {
    building: 'samsung',
    road: 'samsung road',
    city: 'some city',
    country: 'korea',
    pincode: 456677
  }
}
...

limit the number of documents in find

ekart> db.brand_details.find().limit(2)

OUTPUT:
[
  {
    _id: ObjectId("66957f03223aa65aed2ad196"),
    name: 'apple',
    head_office: 'USA',
    products: [ 'mobile', 'laptop', 'tv', 'head phone' ],
    address: {
      building: 'apple company',
      road: 'apple company road',
      city: 'new york',
      country: 'USA',
      pincode: 678899
    }
  },
  {
    _id: ObjectId("669581b1223aa65aed2ad197"),
    name: 'samsung',
    head_office: 'korea',
    products: [ 'mobile', 'laptop', 'tv', 'smart watches' ],
    address: {
      building: 'samsung',
      road: 'samsung road',
      city: 'some city',
      country: 'korea',
      pincode: 456677
    }
  }
]

Projection

find/Query specific columns

ekart> db.brand_details.find({},{name:1,founder:1})

OUTPUT:
[
  {
    _id: ObjectId("66957f03223aa65aed2ad196"),
    name: 'apple',
    founder: 'faf'
  },
  {
    _id: ObjectId("669581b1223aa65aed2ad197"),
    name: 'samsung',
    founder: 'john deo'
  },
  {
    _id: ObjectId("669581b1223aa65aed2ad198"),
    name: 'nokia',
    founder: 'faf'
  }
]

$type find document base on type of specific attribute present

Example : finding all the documents inside the brand_details collections where document having ‘address’ attribute of type ‘object’

ekart> db.brand_details.find( { address: { $type: 'object' } } )

OUTPUT:
[
  {
    _id: ObjectId("66957f03223aa65aed2ad196"),
    name: 'apple',
    head_office: 'USA',
    products: [ 'mobile', 'laptop', 'tv', 'head phone' ],
    address: {
      building: 'apple company',
      road: 'apple company road',
      city: 'new york',
      country: 'USA',
      pincode: 678899
    },
    founder: 'faf'
  },
  {
    _id: ObjectId("669581b1223aa65aed2ad197"),
    name: 'samsung',
    head_office: 'korea',
    products: [ 'mobile', 'laptop', 'tv', 'smart watches' ],
    address: {
      building: 'samsung',
      road: 'samsung road',
      city: 'some city',
      country: 'korea',
      pincode: 456677
    }
]

$exists find document based on attribute exist or not

Example : find the document from ‘brand_details’ collection having ‘stock_price’ attributes in it.Run the below query to update any of the document for ‘stock_price’

ekart> db.brand_details.updateOne(
{ _id: ObjectId(“<specify the object id to update>”)},
{$set:{stock_price:1440.0}}
)

ekart> db.brand_details.find(
 {stock_price :{$exists:true}}
 )

OUTPUT:
[
  {
    _id: ObjectId("66963288223aa65aed2ad1ad"),
    name: 'sony',
    head_office: 'japan',
    products: [ 'Mirrorless camera', 'PlayStation' ],
    address: {
      building: 'sony company',
      road: 'sony company road',
      city: 'tokyo',
      country: 'japan',
      pincode: 101010
    },
    founder: 'akira yamamoto',
    stock_price: 1440
  }
]

Update Single Document

($set)Updating direct attribute

ekart> db.brand_details.updateOne( {name:"nikon"}, {$set:{head_office:"germany"}})

OUTPUT:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

($push)update(example – add) array item inside document

ekart> db.brand_details.updateOne(
 {name:"nikon"},
 {$push:{products:"Mirrorless camera"}})

OUTPUT:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

($set) update the nested object inside the document

 ekart> db.brand_details.updateOne(
 {name:"nikon"},
 {$set:{'address.country':"germany"}})


OUTPUT:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

update all the available document with some common value

ekart> db.brand_details.updateMany({}, { $set: { founder: "john deo" } })

OUTPUT:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 4,
  modifiedCount: 4,
  upsertedCount: 0
}

update with $in

ekart> db.brand_details.updateOne(
 {name:{$in:['nokia','nikon']}},
 {$set:{founder:"maxxy"}}
 )

OUTPUT:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}

Update with multiple conditions

  • Scenario: update the brand_details document by adding new attribute called ranking with value1 where
    1. name =”nikon”
      • or
    2. founder=”john deo”
      • and
      • head_office are germany or japan
ekart> db.brand_details.updateMany( 
{$or:[{name:"nikon"},
{$and:[{founder:"john deo"},{head_office:{$in:['germany','japan']}}]}]},
{$set:{ranking:1}})

OUTPUT:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 4,
  modifiedCount: 4,
  upsertedCount: 0
}

updateMany for all documents

Example: adding two new attribute to all the documents

ekart> db.brand_details.updateMany({}, { $set: { loss: 900 ,profit: 1000 }} )

OUTPUT:
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 16,
  modifiedCount: 16,
  upsertedCount: 0
}

$expr

The $expr operator in MongoDB allows you to use aggregation expressions within the query language. This operator is useful for performing operations like comparing fields within the same document, applying arithmetic operations, and more.

ekart> db.brand_details.find( { $expr: { $lt: ['$profit', '$loss'] } })

OUTPUT:
[
  {
    _id: ObjectId("669629ba223aa65aed2ad1a6"),
    name: 'sony',
    head_office: 'japan',
    products: [ 'Mirrorless camera', 'Compact camera' ],
    address: {
      building: 'sony company',
      road: 'sony company road',
      city: 'osaka',
      country: 'japan',
      pincode: 303030
    },
    founder: 'akira yamamoto',
    loss: 900,
    profit: 600
  },
  {
    _id: ObjectId("669629ba223aa65aed2ad1ab"),
    name: 'sony',
    head_office: 'usa',
    products: [ 'Mirrorless camera', 'Compact camera' ],
    address: {
      building: 'sony company',
      road: 'sony company road',
      city: 'los angeles',
      country: 'usa',
      pincode: 808080
    },
    founder: 'akira yamamoto',
    loss: 900,
    profit: 600
  }
]

$regex

The $regex operator in MongoDB allows you to match strings using regular expressions. This can be useful for searching text fields within your documents based on patterns.

Example Use Cases

  1. Basic Pattern Matching: Finding documents where a field matches a specific pattern.
  2. Case-Insensitive Matching: Searching text fields without regard to case.
  3. Anchoring Matches: Using ^ to match the beginning of a string or $ to match the end of a string.
ekart> db.brand_details.find(
 {founder:{$regex:/^steve/}}
)

OUTPUT:
[
  {
    _id: ObjectId("669629ba223aa65aed2ad1a8"),
    name: 'apple',
    head_office: 'usa',
    products: [ 'DSLR Camera', 'Compact camera' ],
    address: {
      building: 'apple company',
      road: 'apple company road',
      city: 'cupertino',
      country: 'usa',
      pincode: 505050
    },
    founder: 'steve jobs',
    loss: 900,
    profit: 1000
  },
  {
    _id: ObjectId("66963288223aa65aed2ad1ae"),
    name: 'apple',
    head_office: 'usa',
    products: [ 'iPhone', 'MacBook' ],
    address: {
      building: 'apple company',
      road: 'apple company road',
      city: 'cupertino',
      country: 'usa',
      pincode: 95014
    },
    founder: 'steve jobs',
    loss: 900,
    profit: 1000
  }
]

text indexing

Text indexing in MongoDB allows you to perform text searches on string content within your documents. This is particularly useful for applications that require searching through large amounts of text, such as search engines or content management systems.

Steps to Create and Use Text Indexes

  • Create a Text Index: Use the createIndex method to create a text index on the fields you want to search.
ekart> db.brand_details.createIndex(
 {founder:"text"}
 )

OUTPUT:
founder_text
  • Perform Text Searches: Use the $text operator to perform text searches on the indexed fields.
ekart> db.brand_details.find(
 {$text:{$search:"steve"}})

OUTPUT:
[
  {
    _id: ObjectId("66963288223aa65aed2ad1ae"),
    name: 'apple',
    head_office: 'usa',
    products: [ 'iPhone', 'MacBook' ],
    address: {
      building: 'apple company',
      road: 'apple company road',
      city: 'cupertino',
      country: 'usa',
      pincode: 95014
    },
    founder: 'steve jobs',
    loss: 900,
    profit: 1000
  }
]

Aggregation

db.collection.aggregate(pipeline,options)

various keywords, operators, and expression

Here’s a comprehensive list of MongoDB keywords, operators, and expressions, including the previously mentioned and additional ones:

Query Operators

  • $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.
  • $lt: Matches values that are less than a specified value.
  • $lte: Matches values that are less than or equal to a specified value.
  • $ne: Matches all values that are not equal to a specified value.
  • $in: Matches any of the values specified in an array.
  • $nin: Matches none of the values specified in an array.
  • $and: Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
  • $or: Joins query clauses with a logical OR returns all documents that match the conditions of either clause.
  • $not: Inverts the effect of a query expression.
  • $nor: Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
  • $exists: Matches documents that have the specified field.
  • $type: Matches documents if a field is of the specified type.
  • $regex: Provides regular expression capabilities for pattern matching strings.
  • $expr: Allows the use of aggregation expressions within the query language.
  • $mod: Performs a modulo operation on the value of a field and selects documents with a specified result.
  • $text: Performs text search.
  • $where: Matches documents that satisfy a JavaScript expression.
  • $size: Matches any array with the specified number of elements.
  • $all: Matches arrays that contain all elements specified in the query.
  • $elemMatch: Matches documents that contain an array field with at least one element that matches all the specified query criteria.
  • $bitsAllClear: Matches numeric or binary values in which a set of bit positions all have a value of 0.
  • $bitsAllSet: Matches numeric or binary values in which a set of bit positions all have a value of 1.
  • $bitsAnyClear: Matches numeric or binary values in which any bit from a set of bit positions has a value of 0.
  • $bitsAnySet: Matches numeric or binary values in which any bit from a set of bit positions has a value of 1.
  • $jsonSchema: Validates documents against the given JSON Schema.
  • $geoWithin: Selects geometries within a bounding geometry.
  • $geoIntersects: Selects geometries that intersect with a geometry.
  • $near: Returns geospatial objects in proximity to a point.
  • $nearSphere: Returns geospatial objects in proximity to a point on a sphere.
  • $comment: Adds a comment to a query, which can be useful for identifying queries in the profiler logs.

Update Operators

  • $inc: Increments the value of the field by the specified amount.
  • $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.
  • $unset: Removes the specified field from a document.
  • $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.
  • $currentDate: Sets the value of a field to the current date.
  • $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.
  • $each: Modifies the $push and $addToSet operators to append multiple items for array updates.
  • $slice: Limits the number of items in an array.
  • $sort: Sorts elements of an array.
  • $position: Specifies the location in the array at which the $push operator should add elements.
  • $bit: Performs bitwise AND, OR, and XOR operations.
  • $setOnInsert: Assigns a value to a field if an update results in an insert operation (i.e., upsert).
  • $pushAll: (Deprecated) Adds multiple items to an array. Use $push with $each instead.

Aggregation Pipeline Operators

  • $match: Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.
  • $project: Reshapes each document in the stream, such as by adding new fields or removing existing fields.
  • $group: Groups input documents by a specified identifier expression and applies the accumulator expression(s), if specified, to each group.
  • $sort: Sorts all input documents and returns them to the pipeline in sorted order.
  • $limit: Passes the first n documents unmodified to the pipeline where n is the specified limit.
  • $skip: Skips the first n documents where n is the specified skip number and passes the remaining documents unmodified to the pipeline.
  • $unwind: Deconstructs an array field from the input documents to output a document for each element.
  • $lookup: Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing.
  • $out: Writes the resulting documents of the aggregation pipeline to a collection.
  • $bucket: Categorizes incoming documents into groups, called buckets, based on a specified expression and bucket boundaries.
  • $bucketAuto: Automatically categorizes documents into a specified number of buckets, maintaining equal group sizes.
  • $count: Returns a count of the number of documents input to the stage.
  • $facet: Processes multiple aggregation pipelines within a single stage on the same set of input documents.
  • $graphLookup: Performs a recursive search on a collection, with input from the same collection or a different one.
  • $indexStats: Returns statistics regarding the use of each index for collections in the database.
  • $replaceRoot: Replaces the input document with the specified document.
  • $replaceWith: (Alias for $replaceRoot) Replaces the input document with the specified document.
  • $merge: Writes the resulting documents of the aggregation pipeline to a collection, optionally merging documents into the existing collection.
  • $sample: Randomly selects the specified number of documents from its input.
  • $set: Adds new fields to documents. Similar to $addFields.
  • $unset: Removes/excludes fields from documents.
  • $redact: Prunes documents to restrict the contents of the returned documents based on information in the documents themselves.

Text Search Operators

  • $text: Performs text search.
  • $search: Specifies the text to search for.
  • $language: Specifies the language for the text search.
  • $caseSensitive: Enables or disables case-sensitive search.
  • $diacriticSensitive: Enables or disables diacritic-sensitive search.

Geospatial Operators

  • $geoWithin: Selects geometries within a bounding geometry.
  • $geoIntersects: Selects geometries that intersect with a geometry.
  • $near: Returns geospatial objects in proximity to a point.
  • $nearSphere: Returns geospatial objects in proximity to a point on a sphere.

Array Operators

  • $all: Matches arrays that contain all elements specified in the query.
  • $elemMatch: Matches documents that contain an array field with at least one element that matches all the specified query criteria.
  • $size: Matches any array with the specified number of elements.
  • $slice: Limits the number of items in an array returned in a query.

Projection Operators

  • $: Projects the first element in an array that matches the query condition.
  • $elemMatch: Projects the first element in an array that matches the specified $elemMatch condition.
  • $meta: Projects the score assigned during $text query.
  • $slice: Limits the number of elements projected from an array.

Indexes

  • Single Field Index: Indexes on a single field.
  • Compound Index: Indexes on multiple fields.
  • Multikey Index: Indexes the content stored in arrays.
  • Geospatial Indexes: Indexes to support location-based data.
  • Text Indexes: Indexes for text search.
  • Hashed Index: Indexes for hashed data.

This comprehensive list should cover most of the essential MongoDB keywords, operators, and expressions you will encounter.

Leave a Reply

Your email address will not be published. Required fields are marked *