# Mongo[[db|DB]]
- 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()`
- `find` returns a cursor to `it` on
- `toArray` returns an array
- `dp.pets.count({ type: "cat", age: { $gt: 12 } })` , `$gt` is a query operator
- `dp.pets.count({ type: "bird", $and: [ {age: {$gte: 4}}, {age: {$lte: 8}} ] })`
- `dp.pets.find({ type: "dog" }).sort({ age: -1, name: -1 })`, `-1` indicates descending.
- `dp.pets.find({ type: "dog" }, { name: 1, _id: -1 })`, projection, use `1` or `true` and `-1` or `false` to include/exclude fields.
### Update
Use `One` if only updating one.
```js
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
- `deleteOne`
- `findOneAndDelete`, similar to `pop`
### Indexes
- A [[b-tree|B-tree]] is created, complexity reduced from $O(n)$ to $O(\lg n)$
- `...find(...).explain("executionStats")` to view performance details
- `db.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 one `text` index is allowed. `db.pets.find({ $text: {$search: "dog Havanese Luna"} })`, which can be sorted by `textScore`. Full text search.
## Aggregation
```js
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.