下面是我的mongo结构
{
"_id" : ObjectId("5bfbc18e28198e2f74e1d2d0"),
"address" : {
"building" : "1007",
"coord" : [
-73.856077,
40.848447
],
"street" : "Morris Park Ave",
"zipcode" : "10462"
},
"borough" : "Bronx",
"cuisine" : "Bakery"
}
启动db.Restaurant.find({“ address.building”:“ 1007”},{“ address.building”:1,“ address.street”:1,“ address.zipcode”:1}) 查询结果为
{
"_id" : ObjectId("5bfbc18e28198e2f74e1d2d0"),
"address" : {
"building" : "1007",
"street" : "Morris Park Ave",
"zipcode" : "10462"
}
}
答案 0 :(得分:3)
find
查询只能限制字段。如果要重塑数据,则需要使用aggregation
db.collection.aggregate([
{ "$match": { "address.building": "1007" }},
{ "$replaceRoot": { "newRoot": "$address" }},
{ "$project": { "coord": 0 }}
])
答案 1 :(得分:1)
您可以尝试以下汇总。它首先匹配您的任何条件,然后投影必填字段,而不会嵌套。
db.test.aggregate([
{
$match : {
"address.building":"1007"
}
},
{
$project : {
building : "$address.building",
street : "$address.street",
zipcode : "$address.zipcode"
}
}
])
输出:
{
"_id" : ObjectId("5bfbc18e28198e2f74e1d2d0"),
"building" : "1007",
"street" : "Morris Park Ave",
"zipcode" : "10462"
}
让我知道这是否有帮助!