插件窝 干货文章 mongodb如何增删改查语句

mongodb如何增删改查语句

collection javascript 张三 name 574    来源:    2025-03-27

MongoDB 增删改查(CRUD)操作指南

MongoDB 是一个基于文档的 NoSQL 数据库,使用类似 JSON 的 BSON 格式存储数据。以下是 MongoDB 的基本增删改查操作语句:

1. 插入(Insert)操作

插入单个文档

db.collection.insertOne({
  name: "张三",
  age: 25,
  email: "zhangsan@example.com",
  hobbies: ["游泳", "阅读"]
})

插入多个文档

db.collection.insertMany([
  {
    name: "李四",
    age: 30,
    email: "lisi@example.com"
  },
  {
    name: "王五",
    age: 28,
    email: "wangwu@example.com"
  }
])

2. 查询(Query)操作

查询所有文档

db.collection.find()

带条件查询

// 等于条件
db.collection.find({ age: 25 })

// 大于条件
db.collection.find({ age: { $gt: 25 } })

// 小于等于条件
db.collection.find({ age: { $lte: 30 } })

// 多条件AND
db.collection.find({ age: { $gt: 25 }, name: "李四" })

// 多条件OR
db.collection.find({ $or: [{ age: 25 }, { name: "李四" }] })

查询特定字段

db.collection.find({}, { name: 1, email: 1 })

限制结果数量

db.collection.find().limit(5)

排序结果

// 升序
db.collection.find().sort({ age: 1 })

// 降序
db.collection.find().sort({ age: -1 })

3. 更新(Update)操作

更新单个文档

db.collection.updateOne(
  { name: "张三" },
  { $set: { age: 26 } }
)

更新多个文档

db.collection.updateMany(
  { age: { $lt: 30 } },
  { $set: { status: "young" } }
)

替换整个文档

db.collection.replaceOne(
  { name: "张三" },
  {
    name: "张三",
    age: 27,
    email: "newzhangsan@example.com"
  }
)

数组操作

// 添加元素到数组
db.collection.updateOne(
  { name: "张三" },
  { $push: { hobbies: "跑步" } }
)

// 从数组移除元素
db.collection.updateOne(
  { name: "张三" },
  { $pull: { hobbies: "游泳" } }
)

4. 删除(Delete)操作

删除单个文档

db.collection.deleteOne({ name: "张三" })

删除多个文档

db.collection.deleteMany({ age: { $gt: 30 } })

删除集合中的所有文档(保留集合结构)

db.collection.deleteMany({})

5. 索引操作

创建索引

// 单字段索引
db.collection.createIndex({ name: 1 })

// 复合索引
db.collection.createIndex({ name: 1, age: -1 })

// 唯一索引
db.collection.createIndex({ email: 1 }, { unique: true })

查看索引

db.collection.getIndexes()

删除索引

db.collection.dropIndex("name_1")

6. 聚合操作

db.collection.aggregate([
  { $match: { age: { $gt: 25 } } },
  { $group: { _id: "$status", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

以上是 MongoDB 的基本 CRUD 操作语句,实际使用时可以根据具体需求组合这些操作。