{
"_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 grouping
TOP N
Problems, put into SQL database also have corresponding expression, such as SQLServerROW_NUMBER() OVER(PARTITION BY COLUMN ORDER BY COLUMN)
MongoDB
aggregation
It can be solved.aggregation
This 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:
Use
{$sort: {_id: -1}}
In fact, it is the reverse order of time._id
It contains time, and most of the time, it can be regarded as the sort of time.
$first
Got the first element. What if you want to get the first n elements?$push
+$slice
Just do it.How can the above inquiry be faster?
db.chat.createIndex({current_uid: 1, _id: 1})