获取mongo嵌套属性作为列

时间:2019-01-10 12:56:20

标签: mongodb mongoose mongodb-query aggregation-framework

下面是我的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"
    }
}

因此它仍以嵌套文档的形式返回结果,但我想将这些嵌套属性作为列名使用,并且不希望使用嵌套结构。我该如何修改此查询?expected output image

2 个答案:

答案 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"
}

让我知道这是否有帮助!