mongodb查询语句叫什么

MongoDB 中使用 find() 语句进行查询,可根据查询条件筛选文档。语法:db.collection.find(query, projection)。参数包括可选的查询条件(query)和返回字段(projection)。用法:查找所有文档、条件查找、指定返回字段、分页查询、排序结果、查找数组文档、使用正则表达式和逻辑运算符进行复杂查询。

MongoDB 查询语句

MongoDB 使用称为 find() 的查询语句来检索集合中的文档。

语法

db.collection.find(query, projection)

参数

  • query (可选): 用于过滤结果的查询参数,例如 { name: "John" }
  • projection (可选): 用于指定要返回文档中的哪些字段,例如 { name: 1, age: 1 }

用法

1. 查找所有文档

db.collection.find()

2. 根据条件查找文档

db.collection.find({ name: "John" })

3. 指定返回字段

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

4. 分页查询

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

5. 排序结果

db.collection.find().sort({ name: 1 }) // Ascending order
db.collection.find().sort({ name: -1 }) // Descending order

6. 查找文档中的数组

db.collection.find({"arrayField.field": "value"})

7. 使用正则表达式

db.collection.find({ name: /John/i }) // case-insensitive match

8. 使用逻辑运算符

db.collection.find({ $and: [{ name: "John" }, { age: { $gt: 18 }}] }) // AND operator