第2章:MongoDB基本操作
2.1 连接与基本命令
2.1.1 连接方式
mongo
mongo --host localhost --port 27017
mongo -u username -p password --authenticationDatabase admin
2.1.2 数据库操作
show dbs
use myDatabase
db
db.dropDatabase()
2.2 文档增删改查
2.2.1 插入文档
db.users.insertOne({
name: "张三",
age: 30,
email: "zhangsan@example.com",
tags: ["程序员", "90后"]
})
db.users.insertMany([
{name: "李四", age: 25},
{name: "王五", age: 35}
])
db.users.save({
_id: ObjectId("..."),
name: "赵六",
age: 40
})
2.2.2 查询文档
db.users.find()
db.users.find({age: {$gt: 25}})
db.users.find(
{age: {$gt: 25}},
{name: 1, age: 1, _id: 0}
)
db.users.find({
$or: [
{age: {$lt: 30}},
{name: /张/}
]
})
2.2.3 更新文档
db.users.updateOne(
{name: "张三"},
{$set: {age: 31}}
)
db.users.updateMany(
{age: {$lt: 30}},
{$inc: {age: 1}}
)
db.users.replaceOne(
{name: "张三"},
{name: "张三", age: 32, city: "北京"}
)
2.2.4 删除文档
db.users.deleteOne({name: "张三"})
db.users.deleteMany({age: {$lt: 25}})
2.3 游标操作
2.3.1 游标基本使用
db.users.find().limit(5)
db.users.find().skip(3).limit(5)
db.users.find().sort({age: 1})
db.users.find().sort({age: -1})
2.3.2 高级游标
db.users.countDocuments({age: {$gt: 25}})
db.users.distinct("city")
2.4 常用运算符
2.4.1 比较运算符
db.products.find({price: {$eq: 100}})
db.products.find({price: {$gt: 100}})
db.products.find({price: {$gte: 100, $lte: 500}})
2.4.2 逻辑运算符
db.inventory.find({
$and: [
{status: "A"},
{qty: {$lt: 30}}
]
})
db.inventory.find({
$or: [
{status: "A"},
{qty: {$lt: 30}}
]
})