mongodb - Map aggregation results in Mongo -


here data set:

{ "_id" : "1", "key" : "111", "payload" : 100, "type" : "foo", "createdat" : isodate("2016-07-08t11:59:18.000z") } { "_id" : "2", "key" : "111", "payload" : 100, "type" : "bar", "createdat" : isodate("2016-07-09t11:59:19.000z") } { "_id" : "3", "key" : "222", "payload" : 100, "type" : "foo", "createdat" : isodate("2016-07-10t11:59:20.000z") } { "_id" : "4", "key" : "222", "payload" : 100, "type" : "foo", "createdat" : isodate("2016-07-11t11:59:21.000z") } { "_id" : "5", "key" : "222", "payload" : 100, "type" : "bar", "createdat" : isodate("2016-07-12t11:59:22.000z") } 

i have group them key:

db.items.aggregate([{$group: {_id: {key: '$key'}}}]) 

that produces next set:

{ "_id" : { "key" : "111" } } { "_id" : { "key" : "222" } } 

and after have retrieve recent values of foo , bar per each group record. my question optimal way it? can iterate items in javascript , perform additional roundtrip db per each group result. i'm not sure if it's time-efficient.

i not sure optimal way it, easy 1 expand aggregation pipeline like

db.items.aggregate([   {     $group:        {         _id: { key: "$key", type: "$type" },          last: { $max: "$createdat" }        }   },    {      $group:      {        _id: { key: "$_id.key" },        mostrecent: { $push: { type: "$_id.type", createdat: "$last" } }      }    }  ]); 

that collection of documents result into

{ "_id" : { "key" : "222" }, "mostrecent" : [ { "type" : "bar", "createdat" : isodate("2016-07-12t11:59:22z") }, { "type" : "foo", "createdat" : isodate("2016-07-11t11:59:21z") } ] } { "_id" : { "key" : "111" }, "mostrecent" : [ { "type" : "bar", "createdat" : isodate("2016-07-09t11:59:19z") }, { "type" : "foo", "createdat" : isodate("2016-07-08t11:59:18z") } ] } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -