MongoDB
- Database vs collections
- Documents (records) = one entry in the collections
- MongoDB creates IDs for documents automatically
Queries
Find
dp.pets.find({ type: "dog" }).limit(5).toArray()findreturns a cursor toitontoArrayreturns an array
dp.pets.count({ type: "cat", age: { $gt: 12 } }),$gtis a query operatordp.pets.count({ type: "bird", $and: [ {age: {$gte: 4}}, {age: {$lte: 8}} ] })dp.pets.find({ type: "dog" }).sort({ age: -1, name: -1 }),-1indicates descending.dp.pets.find({ type: "dog" }, { name: 1, _id: -1 }), projection, use1ortrueand-1orfalseto include/exclude fields.
Update
Use One if only updating one.
dp.pets.updateOne({
{ type: "dog", ... }, // query object
{ $set: { owner: "Brain Holt" } }
})
dp.pets.updateMany({
{ type: "dog" }, // query object
{ $inc: { age: 1 } }
})
dp.pets.updateMany({
{ type: "dog" }, // query object
{ $set: { ... } },
{ upsert: true } // insert if not exist, using the $set object
})Delete
deleteOnefindOneAndDelete, similar topop
Indexes
- A B-tree is created, complexity reduced from to
...find(...).explain("executionStats")to view performance detailsdb.pets.createIndex( { name: 1 } )db.pet.getIndexies()db.pet.createIndex( {index: 1}, {unique: true} )to create unique indices.db.pets.createIndex({type: "text", breed: "text", name: "text"}), only onetextindex is allowed.db.pets.find({ $text: {$search: "dog Havanese Luna"} }), which can be sorted bytextScore. Full text search.
Aggregation
db.pets.aggregate([
{ $match : { type: "dog" } }, // first stage in pipeline
{
$bucket: {
groupBy: $age",
boundaries: [0, 3, 9, 15], // bottom included, top excluded
default: "16+",
output: { count: { $sum: 1 } } // similar to projection
}
},
{ $sort: { count: -1 } } // final stage
])Ops
- Replica set
- Primary - read and write to
- Secondaries - transactions in primary are flushed to secondaries, “eventually consistent”
- When primary goes down, an election is made to choose new primary.