对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

字段路径

使用 字段路径(Field Path)表达式访问输入文档中的字段。在字段名称或 虚线字段路径(Field Path)(对于嵌入式文档)前加上美元符 $。

以下示例使用 Atlas 示例数据库 中的 planets 集合。此集合中的每个文档都具有以下结构:

{ _id: new ObjectId("6220f6b78a733c51b416c80e"), name: "Uranus", orderFromSun: 7, hasRings: true, mainAtmosphere: [ "H2", "He", "CH4" ], surfaceTemperatureC: { min: null, max: null, mean: -197.2 }}

要在 surfaceTemperatureC 内指定嵌套的 mean 字段,请使用带有美元符 $ 的 点表示法 ("field.nestedField")。此聚合管道仅投影每个文档的 mean 嵌套字段值:

db.planets.aggregate( [ { $project: { nested_field: "$surfaceTemperatureC.mean" } }] )

返回文档示例:

{ _id: ObjectId('6220f6b78a733c51b416c80e'), nested_field: -197.2 }

在字段路径(Field Path)中使用 点表示法来访问嵌套在数组中的字段。例如,考虑一个 products 集合,其 instock 字段包含一个嵌套 warehouse 字段的数组:

db.products.insertMany( [ { item: "journal", instock: [ { warehouse: "A"}, { warehouse: "C" } ] }, { item: "notebook", instock: [ { warehouse: "C" } ] }, { item: "paper", instock: [ { warehouse: "A" }, { warehouse: "B" } ] }, { item: "planner", instock: [ { warehouse: "A" }, { warehouse: "B" } ] }, { item: "postcard", instock: [ { warehouse: "B" }, { warehouse: "C" } ] }] )

以下聚合管道使用 $instock.warehouse访问权限嵌套的 warehouse 字段。

db.products.aggregate( [ { $project: { item: 1, warehouses: "$instock.warehouse" } }] )

在此示例中,$instock.warehouse 输出每个文档的嵌套 warehouse字段中的值的大量。 管道返回以下文档:

[ { _id: ObjectId('6740b55e33b29cf6b1d884f7'), item: "journal", warehouses: [ "A", "C" ] }, { _id: ObjectId('6740b55e33b29cf6b1d884f8'), item: "notebook", warehouses: [ "C" ] }, { _id: ObjectId('6740b55e33b29cf6b1d884f9'), item: "paper", warehouses: [ "A", "B" ] }, { _id: ObjectId('6740b55e33b29cf6b1d884fa'), item: "planner", warehouses: [ "A", "B" ] }, { _id: ObjectId('6740b55e33b29cf6b1d884fb'), item: "postcard", warehouses: [ "B", "C" ] }]

还可以在字段路径(Field Path)中使用带有美元符号 $ 的点表示法来访问嵌套数组中的数组。以下示例使用包含此文档的 fruits 集合:

db.fruits.insertOne( { _id: ObjectId("5ba53172ce6fa2fcfc58e0ac"), inventory: [ { apples: [ "macintosh", "golden delicious", ] }, { oranges: [ "mandarin", ] }, { apples: [ "braeburn", "honeycrisp", ] } ] })

以下聚合管道访问 inventory 内的嵌套 apples 数组:

db.fruits.aggregate( [ { $project: { all_apples: "$inventory.apples" } }] )

在此管道中,$inventory.apples 解析为一个由嵌套数组组成的大量。 管道返回以下文档:

{ _id: ObjectId('5ba53172ce6fa2fcfc58e0ac'), all_apples: [ [ "macintosh", "golden delicious" ], [ "braeburn", "honeycrisp" ] ]}

有关访问嵌套元素并与之交互的更多信息,请参阅点表示法和查询嵌入式文档数组。