使用 字段路径(Field Path)表达式访问权限输入文档中的字段。在字段名称或虚线字段路径(Field Path)(针对嵌入式文档)前面加上美元符号$ 。
嵌套字段
以下示例使用Atlas样本数据库中的 行星集合。此集合中的每个文档都具有以下结构:
{ _id: new ObjectId("6220f6b78a733c51b416c80e"), name: "Uranus", orderFromSun: 7, hasRings: true, mainAtmosphere: [ "H2", "He", "CH4" ], surfaceTemperatureC: { min: null, max: null, mean: -197.2 } }
要指定mean 中的嵌套surfaceTemperatureC "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" ] ] }