默认情况下,MongoDB的查询语句返回匹配到文档的所有字段,为了限制MongoDB返回给应用的数据,可以通过文档来指定或限制返回的字段。
本文提供了使用mongo shell中方法映射查询的案例。案例中使用的inventory集合数据可以通过下面的语句产生。
db.inventory.insertMany( [
{ item: "journal", status: "A", size: { h: 14, w: 21, uom: "cm" }, instock: [ { warehouse: "A", qty: 5 } ] },
{ item: "notebook", status: "A", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "C", qty: 5 } ] },
{ item: "paper", status: "D", size: { h: 8.5, w: 11, uom: "in" }, instock: [ { warehouse: "A", qty: 60 } ] },
{ item: "planner", status: "D", size: { h: 22.85, w: 30, uom: "cm" }, instock: [ { warehouse: "A", qty: 40 } ] },
{ item: "postcard", status: "A", size: { h: 10, w: 15.25, uom: "cm" }, instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
]);
返回匹配文档中的所有字段
如果没有特别指定, 方法将会返回匹配文档的所有字段。
下面的案例返回inventory集合中status等于**"A"**的文档的所有字段。
db.inventory.find( { status: "A" } )
上述操作等价于下面的标准SQL:
SELECT * from inventory WHERE status = "A"
仅返回指定字段和_id字段
映射会返回在映射文档中显示设置为1的字段。
下面的案例返回所有检索到文档中item, status, _id三个字段。
db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
上述操作等价于下面的标准SQL:
SELECT _id, item, status from inventory WHERE status = "A"
去除_id字段
可以通过在映射文档中将_id字段设置为0来从结果集中去除 _id字段,就像下面的例子:
db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
上述操作等价于下面的标准SQL:
SELECT item, status from inventory WHERE status = "A"
Note:
除_id字段外,不能在映射文档中同时使用包含和去除语句。
去除指定字段
可以使用映射来排除特定字段,而不是在匹配文档中列出要返回的字段。
下面的案例返回匹配文档中除status 和 instock 字段之外的所有字段:
db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )
Note:
除_id字段外,不能在映射文档中同时使用包含和去除语句。
返回嵌套文档中的指定字段
下面的案例返回
uom字段是size嵌套文档中的字段.
db.inventory.find(
{ status: "A" },
{ item: 1, status: 1, "size.uom": 1 }
)
去除嵌套文档中的指定字段
下面的案例返回匹配文档中除嵌套文档size中的uom字段外的所有字段。
db.inventory.find(
{ status: "A" },
{ "size.uom": 0 }
)
映射数组中的嵌套文档的指定字段
下面案例返回:
db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )
映射返回数组中指定的数组元素
db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )
举个例子,不能使用数组下标来映射指定的数组元素。例如:**{ "instock.0": 1 }**映射不会用第一个元素来映射数组。
参考:
3323
原文链接:https://docs.mongodb.com/manual/tutorial/project-fields-from-query-results/
译者:张芷嘉