查询文档
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( {} )
上述操作对应如下SQL语句:
SELECT * FROM inventory
{ <field1>: <value1>, ... }
下面的案例返回inventory集合中status等于"D"**的所有文档:
db.inventory.find( { status: "D" } )
上述操作对应如下SQL语句:
SELECT * FROM inventory WHERE status = "D"
{ <field1>: { <operator1>: <value1> }, ... }
下面的案例返回inventory集合中status等于**"A"或"D"**的所有文档。
db.inventory.find( { status: { $in: [ "A", "D" ] } } )
上述操作对应如下SQL:
SELECT * FROM inventory WHERE status in ("A", "D")
可以指定文档中的多个字段作为查询条件。在查询语句中使用AND连接多个查询条件来检索集合中满足所有查询条件的文档。
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
上述操作对应如下SQL:
SELECT * FROM inventory WHERE status = "A" AND qty < 30
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
上述操作对应如下SQL:
SELECT * FROM inventory WHERE status = "A" OR qty < 30
Note:
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:
其他查询案例:
游标
读隔离
新增加于MongoDB3.2版本
下面的方法也可以从集合中查询文档:
Note:
原文链接:https://docs.mongodb.com/manual/tutorial/query-documents/
译者:张芷嘉
最近更新 1yr ago