Pete
Pete

Reputation: 13

MongoDB projection on nested array

My documents look like this:

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

How can I project a table with time and duration (one line per array element) only?

The best I could get without errors was this:

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

Upvotes: 0

Views: 946

Answers (1)

s7vr
s7vr

Reputation: 76004

You will need to use aggregation to flatten the array and project the values.

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

Upvotes: 2

Related Questions