mongoDB查询语句

下面是一些常用的 MongoDB 查询语句,适用于日常开发和数据操作,包括查找、插入、更新和删除等操作:


🔍 1. 查找文档(find)

查找全部文档:

lua 复制代码
db.collection.find()

条件查询(等于):

css 复制代码
db.collection.find({ key: "value" })

多条件查询(AND):

php 复制代码
db.collection.find({ key1: "value1", key2: "value2" })

OR 查询:

css 复制代码
db.collection.find({ $or: [{ key1: "value1" }, { key2: "value2" }] })

比较操作符:

php 复制代码
// 小于
db.collection.find({ age: { $lt: 30 } })

// 大于等于
db.collection.find({ age: { $gte: 18 } })

包含在数组中:

css 复制代码
db.collection.find({ tags: { $in: ["mongodb", "database"] } })

模糊查询(正则):

css 复制代码
db.collection.find({ name: { $regex: "^A" } }) // 以 A 开头

✨ 2. 投影字段(只返回部分字段)

php 复制代码
db.collection.find({ age: { $gt: 18 } }, { name: 1, age: 1, _id: 0 })

📊 3. 排序、限制和跳过

scss 复制代码
// 按 age 升序排序
db.collection.find().sort({ age: 1 })

// 按 age 降序排序并只返回前 5 条
db.collection.find().sort({ age: -1 }).limit(5)

// 跳过前 10 条,取 5 条
db.collection.find().skip(10).limit(5)

✏️ 4. 插入文档

插入一条:

php 复制代码
db.collection.insertOne({ name: "Tom", age: 25 })

插入多条:

php 复制代码
db.collection.insertMany([
  { name: "Jerry", age: 22 },
  { name: "Anna", age: 28 }
])

🔧 5. 更新文档

更新一条(只更新第一个匹配项):

css 复制代码
db.collection.updateOne(
  { name: "Tom" },
  { $set: { age: 30 } }
)

更新多条:

css 复制代码
db.collection.updateMany(
  { age: { $lt: 20 } },
  { $set: { status: "minor" } }
)

❌ 6. 删除文档

删除一条:

css 复制代码
db.collection.deleteOne({ name: "Tom" })

删除多条:

css 复制代码
db.collection.deleteMany({ age: { $lt: 18 } })

📌 7. 计数 / 去重

统计数量:

css 复制代码
db.collection.countDocuments({ age: { $gt: 20 } })

去重字段值:

vbnet 复制代码
db.collection.distinct("name")

如果你有具体的应用场景,比如查询嵌套字段、数组字段、聚合分析等,我也可以给你举更复杂的例子!需要吗?

相关推荐
`林中水滴`1 分钟前
MongoDB系列:MongoDB 分片集群环境搭建
mongodb
Msshu1239 小时前
Type-C 多协议快充诱骗电压芯片XSP28 芯片脚耐压高达21V 电路简单 性价比高
mongodb·zookeeper·rabbitmq·flume·memcache
hexiekuaile18 小时前
mongodb8.2知识
mongodb
The Sheep 202321 小时前
MongoDB与.Net6
数据库·mongodb
点灯小铭1 天前
基于单片机的智能收银机模拟系统设计
单片机·嵌入式硬件·mongodb·毕业设计·课程设计·期末大作业
数据知道1 天前
一文掌握 MongoDB 存储引擎 WiredTiger 的原理
数据库·mongodb·数据库架构
清风6666662 天前
基于单片机的电加热炉智能温度与液位PID控制系统设计
单片机·嵌入式硬件·mongodb·毕业设计·课程设计·期末大作业
列御寇2 天前
MongoDB分片集概述
数据库·mongodb
列御寇2 天前
MongoDB分片集群——集群组件概述
数据库·mongodb
列御寇2 天前
MongoDB分片集群——mongos组件(mongos进程)
数据库·mongodb