MongoDB

Document

Syntax:

{
	"key":value,
	"key":value,
	"key":value
}

Example :

{
	"_id": 1,
	"name": "AC3 Phone",
	"colors" : ["black", "silver"],
	"price" : 200,
	"available" : true
}

Connection String components

mongodb://username:password@host[:port]?<options>

Commands

CRUD Operations

Insert

Find

Comparison operators

These can be used with find commands

Example :

db.sales.find(
    { "customer.age" :
      { $gt: 50 }
    }
  )

Querying Arrays

Logical Operators

Replace

Update

updateMany

db.<collection>.updateOne(
    <filter>, <update>, {options}
  )

Example

db.books.updateMany(
  { year : 2023 },
  { $set : { instock : true }}
)

findAndModify

db.<collection>.findAndModify({
query: <filter>,
update: <update>,
new: <boolean value>
})

db.birds.findAndModify({
query: { common_name: "Blue Jay"},
update: { $inc : { sightings_count:1 } },
new :true,
})

Delete

Sorting & limiting

sort

db.collection.find(<query>).sort(<sort>)

Example :

db.companies.find(
  {category_code:"music"}
)
.sort(
  {name:1}
)

limit

Projection

db.collection.find(
   <query>, <projection>
)

count

Aggregation

db.collection.aggregate([
  { $stage_name: {<expression >} },
  { $stage_name: {<expression >} }
])

different stages are

Data modeling

Data that is accessed together should be stored together

types of relationships

Modeling Data Relationship

Multi document transaction

Index

Single key index

db.collection.createIndex({fieldName:1})

Compound key index

db.collection.createIndex({<fieldName>:1, <fieldName>:1, ...})

Multikey index

db.collection.createIndex({<fieldName of array>:1, <fieldName>:1, ...})

Search Index

{
  $search:{
    "index":<index-name>,
    <operator-name> | <collector-name>:{
      <operator-specification> | <collector-specification>
    },
    "highlight":{
      <highlight-option>
    },
    "count":{
      <count-option>
    },
    "returnStoredSource": true | false
  }
}

ACID Transactions