MongoDB 聚合管道:查找并显示层级 JSON 串的指定属性
在 MongoDB 中,可以使用聚合管道操作符 $project 和 $jsonSchema 来查找并显示层级 JSON 串中的指定属性。
假设有以下示例集合 data:
[
{
"_id": 1,
"name": "John",
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY"
}
},
{
"_id": 2,
"name": "Jane",
"address": {
"street": "456 Elm St",
"city": "Los Angeles",
"state": "CA"
}
}
]
下面的示例将查找 address 字段中的 city 属性,并显示层级 JSON 串中的指定属性:
db.data.aggregate([
{
$project: {
_id: 0,
city: "$address.city"
}
}
])
运行上述聚合管道后,将会得到以下结果:
[
{
"city": "New York"
},
{
"city": "Los Angeles"
}
]
在 $project 阶段中,使用 $address.city 来指定要显示的属性路径。_id: 0 用于排除默认的 _id 字段。
这样,就可以在 MongoDB 中查找并显示层级 JSON 串中的指定属性。
原文地址: https://www.cveoy.top/t/topic/iSvy 著作权归作者所有。请勿转载和采集!