How does mongodb retrieve the user chat list when storing instant chats

  mongodb, question
{
 "_id" : ObjectId("576cfd363325ffaa1dbdde15"),
 "current_uid" : "5",
 "to_uid" : "3",
 "content": "Your uncle"
 },
 {
 "_id" : ObjectId("576cfd6e3325ff501e07f4ae"),
 "current_uid" : "5",
 "to_uid" : "3",
 "content": "Guo Degang"
 },
 {
 "_id" : ObjectId("576cfe753325ff501ea76603"),
 "current_uid" : "5",
 "to_uid" : "4",
 "content" : "325235"
 }

When saving, as shown above, I want to get the user ID of 5 who talked to, that is, 3 and 4. Now I want to get the information including the content, that is, the latest record with the user, such as 3. What I want to get is the content of Guo Degang instead of the one above. How should I query this? Beginners mongodb and ball help

This is a very typical groupingTOP NProblems, put into SQL database also have corresponding expression, such as SQLServer

ROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)

MongoDBaggregationIt can be solved.aggregationThis is a very big topic. I can’t explain all the contents here. The various operators used below can only look up the documents and understand them by themselves.

db.chat.aggregate([
 {$match: {current_uid: "5"}},
 {$sort: {_id: -1}},
 {$group: {_id: {current_uid: "$current_uid", to_uid: "$to_uid"}, content: {$first: "$content"}}}
 ])

Several explanations:

  1. Use{$sort: {_id: -1}}In fact, it is the reverse order of time._idIt contains time, and most of the time, it can be regarded as the sort of time.

  2. $firstGot the first element. What if you want to get the first n elements?$push+$sliceJust do it.

  3. How can the above inquiry be faster?db.chat.createIndex({current_uid: 1, _id: 1})