目录
查询文档
本文主要讲述 db.collection.find()
方法,通过inventory集合演示,预先插入数据:
db.inventory.insertMany([
{ item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
{ item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
{ item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
{ item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
{ item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
]);
查询集合所有文档
给find()方法传入空的查询结构参数{},如:
db.inventory.find( {} )
MongoDB的该操作类似以下SQL:
SELECT * FROM inventory
指定equal相等条件查询
以<field>:<value>表达式的形式给定相等条件,即查询字段为某值的文档:
{ <field1>: <value1>, ... }
查询inventory集合中status="D"的文档:
db.inventory.find( { status: "D" } )
类似以下SQL:
SELECT * FROM inventory WHERE status = "D"
通过操作符指定查询条件
可用的操作符参见:https://docs.mongodb.com/manual/reference/operator/query/#query-selectors
使用操作符的过滤查询结构形式如下:
{ <field1>: { <operator1>: <value1> }, ... }
$in操作符获取inventory集合中所有status等于“A”和“D”的文档:
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
$in为 and的关系,也可使用$or操作符执行or关系查询,上面语句类似SQL:
SELECT * FROM inventory WHERE status in ("A", "D")
指定AND条件
一个组合查询可以指定多个条件,这些条件可涉及多个字段。也就是说逻辑与操作将每个查询条件组合起来,使得查询结果满足所有组合条件,如查询status=“A”且qty<30的文档:
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
类似SQL:
SELECT * FROM inventory WHERE status = "A" AND qty < 30
指定OR条件
使用$or运算符实现逻辑或查询,如查询status=“A”或者qty<30的文档:
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
类似SQL:
SELECT * FROM inventory WHERE status = "A" OR qty < 30
同时指定AND和OR条件
如查询status=“A”且满足qty<30或者item以‘p’字符开头的所有文档:
db.inventory.find( {
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )
类似SQL:
SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")
NOTE
MongoDB supports regular expressions $regex
queries to perform string pattern matches.支持正则表达式。
其他的查询
其他的查询可以参见后面章节内容:
- Query on Embedded/Nested Documents
- Query an Array
- Query an Array of Embedded Documents
- Project Fields to Return from Query
- Query for Null or Missing Fields
查询行为
游标(Cursor)
db.collection.find()
方法将返回命中查询条件的文档游标cursor。
读隔离(read isolation)
For reads to replica sets and replica set shards, read concern allows clients to choose a level of isolation for their reads. For more information, see Read Concern.
其他方法
以下方法也可以读取文档:
db.collection.findOne
- In aggregation pipeline, the
$match
pipeline stage provides access to MongoDB queries.
db.collection.findOne()
方法返回命中条件的一个文档,内部是通过db.collection.find()
方法指定limit参数等于1实现的。