2017-03-01 114 views
0

我的文件是這樣的:MongoDB的投影

{ 
    "_id" : ObjectId("58b714f753e4a2105c002416"), 
    "routes" : [ 
     { 
      "legs" : [ 
       { 
        "duration" : { 
         "text" : "6 mins", 
         "value" : 348 
        }, 
        "traffic_speed_entry" : [], 
       } 
      ], 
      "warnings" : [], 
     } 
    ], 
    "time" : "01/03/2017 18:37:43" 
} 

我怎麼能投射出表,時間和持續時間(每個數組元素一個行)只?

我能得到沒有錯誤,最好是這樣的:

db.getCollection('testcoll').find({}, {time:1, routes: 1}) 

回答

1

您需要使用聚合扁平化陣列和項目的值。

db.getCollection('testcoll').aggregate({ 
    $unwind: "$routes" 
}, { 
    $unwind: "$routes.legs" 
}, { 
    $project: { 
     time: 1, 
     duration: "$routes.legs.duration", 
     _id: 0 
    } 
})