MongoDB Project(投影字段)

概述

默认情况下,MongoDB中的查询返回匹配文档中的所有字段。 要限制MongoDB发送给应用程序的数据量,可以包含一个投影文档以指定或限制要返回的字段。

本文提供使用mongo shell中的db.collection.find()方法进行投影的查询操作示例。 此页面上的示例使用库存收集。 要填充库存收集,请运行以下命令:

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 } ] }
]);

1、返回匹配文档中的所有字段

如果没有指定投影文档,db.collection.find()方法将返回匹配文档中的所有字段。

下面的示例返回库存集合中状态为“A”的所有文档的所有字段:

db.inventory.find( { status: "A" } )

2、仅返回指定的字段和_id字段

通过将投影文档中的设置为1,投影可以显式包括多个字段。
以下操作返回与查询匹配的所有文档。 在结果集中,只有item,status以及默认情况下_id字段会返回到匹配的文档中。

db.inventory.find( { status: "A" }, { item: 1, status: 1 } )
#对应的sql:
SELECT _id, item, status from inventory WHERE status = "A"

3、不返回_id字段

您可以通过将投影中的_id字段设置为0来从结果中删除_id字段,如以下示例所示:

db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )

#对应的sql:
SELECT item, status from inventory WHERE status = "A"

注意:
除了_id字段外,您不能在投影文档中对字段进行既包含又排除

#此种不允许
db.inventory.find( { status: "A" }, { item: 1, status: 0} )
#此种允许,表示仅返回item以及status字段
db.inventory.find( { status: "A" }, { item: 1, status: 1} )
#此种允许,表示除了item以及status字段,其它都返回
db.inventory.find( { status: "A" }, { item: 0, status: 0} )

4、返回所有但排除的字段

您可以使用投影排除特定字段,而不是列出要在匹配文档中返回的字段。 以下示例返回匹配文档中状态和库存字段以外的所有字段:

db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )

5、返回嵌入文档中的特定字段

您可以在嵌入的文档中返回特定的字段。使用点符号来引用嵌入的字段,并在投影文档中将其设置为1。

下面的例子返回:

  • _id 字段 (returned by default),
  • item 字段,
  • status字段,
  • size 子文档中的uom字段
db.inventory.find(
   { status: "A" },
   { item: 1, status: 1, "size.uom": 1 }
)

6、在嵌入的文档中禁止特定的字段

可以在嵌入式文档中禁用特定字段。使用点符号来引用投影文档中的嵌入字段,并将其设置为0。

db.inventory.find(
   { status: "A" },
   { "size.uom": 0 }
)

7、在数组中嵌入文档上的投影

使用点表示法来投影嵌入在数组中的文档中的特定字段。

下面的例子指定了一个要返回的投影:

  • _id 字段 (returned by default),
  • item 字段,
  • status字段,
  • 嵌入在instock数组中的文档中的qty字段。
db.inventory.find( { status: "A" }, { item: 1, status: 1, "instock.qty": 1 } )

8、投影返回数组中的特定数组元素

对于包含数组的字段,MongoDB为操作数组提供了以下投影操作符: $ elemMatch、$ slice和$。

下面的例子使用$slice投影操作符来返回instock数组中的最后一个元素:

db.inventory.find( { status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } } )

$ elemMatch,$ slice和$是投影要包含在返回数组中的特定元素的唯一方法。
例如,您不能使用数组索引来投影特定的数组元素。
例如 {“ instock.0”:1}投影不会投影第一个元素的数组。

发布了111 篇原创文章 · 获赞 0 · 访问量 2076

猜你喜欢

转载自blog.csdn.net/weixin_38932035/article/details/105139859
今日推荐