The data obtained by grouping and summing MongoDB includes other field data

  mongodb, question

The following data exists in the user collection in mongodb:

{uid: "1","vn": "LB23","time": "2017-10-01","record": 123}
 {uid: "1","vn": "LB24","time": "2017-10-03","record": 133}
 {uid: "1","vn": "LB24","time": "2017-10-02","record": 123}
 {uid: "1","vn": "LB24","time": "2017-10-04","record": 1222}
 {uid: "1","vn": "LB25","time": "2017-10-01","record": 123}
 {uid: "1","vn": "LB25","time": "2017-10-02","record": 1223}

The result is that the maximum time data is counted according to vn and then the sum of record is counted. However, the maximum number of times is calculated by grouping when querying, and then the total number is calculated according to subdocuments.

{ "$group" : { "_id" : { "vn" : "$vn" } , "collect_time" : { "$max" : "$time"}}}

The data set obtained through this command is:

{“_id”:{"vn":"LB25"},"time":"2017-10-02"}
 {“_id”:{"vn":"LB24"},"time":"2017-10-04"}
 ...

Record data is not included here. How can I modify it?

In this way of thinkingaggregationGrammar is not easy to write, but it is easy to write in a different way:

db.test.insert([
 {uid: "1","vn": "LB23","time": "2017-10-01","record": 123},
 {uid: "1","vn": "LB24","time": "2017-10-03","record": 133},
 {uid: "1","vn": "LB24","time": "2017-10-02","record": 123},
 {uid: "1","vn": "LB24","time": "2017-10-04","record": 1222},
 {uid: "1","vn": "LB25","time": "2017-10-01","record": 123},
 {uid: "1","vn": "LB25","time": "2017-10-02","record": 1223}
 ])
 db.test.aggregate([
 {$sort: {vn: 1, time: -1}},
 {$group: {_id: "$vn", doc: {$first: "$$ROOT"}}},
 ])

That is, according tovnAndtimeArrange the order first, then take each individualvnThe first piece of data of (that is, the one with the largest time).
The output is (I took out the entire file for simplicity, please adjust it as needed):

{ "_id" : "LB25", "doc" : { "_id" : ObjectId("59ed572a70650b44dccaf986"), "uid" : "1", "vn" : "LB25", "time" : "2017-10-02", "record" : 1223 } }
 { "_id" : "LB24", "doc" : { "_id" : ObjectId("59ed572a70650b44dccaf984"), "uid" : "1", "vn" : "LB24", "time" : "2017-10-04", "record" : 1222 } }
 { "_id" : "LB23", "doc" : { "_id" : ObjectId("59ed572a70650b44dccaf981"), "uid" : "1", "vn" : "LB23", "time" : "2017-10-01", "record" : 123 } }

Proper index can speed up your access speed:

db.test.createIndex({vn: 1, time: -1});