Skip to main content

MongoDB 实践

Concept & Tools

Structure

  • Document
  • Collection
  • Database

Tools

  • Mongo Compass
  • Mongosh

Commands

Basic

show dbs
use <db name> # Switch db

use <db name not exist> # Create new db

db.createCollection("students") # Create collection

db.droptDatabase() # Delete current database
db.students.insertOne({name: "Spongebob", age: 30, gpa: 3.2}) # Insert one document
db.students.find() # Get documents
db.students.insertMany([{name: "Patrick", age: 38, gpa: 1,5}, {name: "Snady", age: 27, gpa: 4.0}, {name: "Gary", age: 18, gpa: 2.5}])

Data Types

db.students.insertOne({name: "Larry", age:32, gpa: 2.8, ...})
  • name: string
  • age: number
  • gpa: double
  • fullTime: boolean
  • registerDate: new Date()
  • gradutionDate: null
  • courses: array
  • nest document -> address: {street: "123 Fake St.", city: "Bikini Bottom", zip: 12345}

Sort and Limit

db.students.find().sort({name: 1})
db.students.find().sort({name: -1})

db.students.find().limit(1)

db.students.find().sort({gpt:-1}).limit(1)

Find method

.find({query})

db.students.find()
db.students.find({name: "Spongebob"})
db.students.find({gpa: 4.0})
db.students.find({fullTime: false})
db.students.find({gpa: 4.0, fullTime: true})

.find({query, projection})

db.students.find({}, {name: true}) # Get _id and name field
db.students.find({}, {_id: false, name: true}) # Get just name field

Update documents

.updateOne(filter, udpate)

db.students.updateOne({name: "Spongebob"}, {$set: {fullTime: true}})
db.students.updateOne({_id: ObjectId("123iufbsduiwkje")}, {$set: {fullTime: false}})
db.students.updateOne({_id: ObjectId("123iufbsduiwkje")}, {$unset: {fullTime: ""}}) # Delete the field fullTime

db.students.updateMany({}, {$set: {fullTime: false}}) # Set all documents fullTime as false
db.students.updateOne({name: "Gary", {$unset: {fullTime: ""}})

db.students.updateMany({fullTime: {$exists: false}}, {$set: {fullTime: true}})

Delete documents

db.students.deleteOne({name: "Larry"})
db.students.deleteMany({fullTime: false})

db.students.deleteMany({registerDate: {$exists: false}}) # Delete students documents without registerDate

Comparison operators

db.students.find({name: "Spongebob"})
db.students.find({name: {$ne: "Spongebob"}}) name != "Spongebob"

db.students.find({age: {$lt: 20}}) # age < 20
db.students.find({age: {$lte: 27}}) # age <= 27
db.students.find({age: {$gt: 27}}) # age > 27
db.students.find({age: {$gte: 27}}) # age >= 27
db.students.find({gpa: {$gte: 3, $lte: 4}}) # >=3, <= 4

db.students.find({name: {$in: ["Spongebob", "Patrick", "Sandy"]}})
db.students.find({name: {$nin: ["Spongebob", "Patrick", "Sandy"]}})

Logical Query Operators

  • $and
  • $nor
  • $or
  • $not
db.students.find({$and: [{fullTime: true}, {age: {$lte: 22}}]})
db.students.find({$or: [{fullTime: true}, {age: {$lte: 22}}]})

db.students.find({$nor: [{fullTime: true}, {age: {$lte: 22}}]}) # both condition must be false

db.students.find({age: {$lt: 30}}) # age < 30
db.students.find({age: {$not: {$gte: 30}}}) # age < 30, event age is null

Indexes

B-Tree

db.students.find({name: "Larry"}).explean("executionStats") # 解释运行过程

db.students.createIndex({name: 1}) # Ascending
db.students.createIndex({name: -1}) # Descending

db.students.getIndex() # Get indexes of colelction
db.students.dropIndex("name_1") # Drop by index name

Collection

show collections

db.createCollection("teachers", {capped: true, size: 10000000, max: 100}, {autoIndexId: false})

db.createCollection("courses")
db.courses.frop()

Aggregation

- {$sort: {<column>: <1 or -1>}}
- {$limit: 4}
- {$project: {name: 1, age: -1}}
- {$group: {_id: null, averageAge: {$avg: "$age"}}}
- [{$match": {tags: "enim"}}, {$count: "userWithEnimTag"}] -> userWithEnimTag: <number of documents>
- {$group: {_id: "$name", users: {$push: "$name"}}}
- [{$match: {"tags.1": "ad"}}, {$count: "secondTagAsAd"}] -> second tags is "ad"
- {$match}: {tags: {$all: ["enim", "id"]}}
- [{$match: {"company.location.country": "USA"}}, {$group: {_id: "$company.title", userCount: {$sum: 1}}}]
- [{$lookup: {from: "authors", localField: "author_id", foreignField: "\_id", as: "author_details"}}, {$addFields: {author_details: {$first: "$author_details"}}}]
- [{$lookup: {from: "authors", localField: "author_id", foreignField: "\_id", as: "author_details"}}, {$addFields: {author_details: {$arrayElemAt: ["$author_details", "0"]}}}]