![](/img/trans.png)
[英]Hot to get last 30 records of collection result in mongodb, but not from zero?
[英]Query in mongoDB to get records with different value and last added
我有這樣的人妖:
var messageSchema = system.mongoose.Schema({
from: {
type: system.mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
to: {
type: system.mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
content: {
type: String,
required: true
},
createDate: {
type: Date,
default: Date.now
}
});
如何創建查詢以僅獲取每個用戶的最后一條消息?
您可以使用聚合查詢
db.collection.aggregate([
{ "$sort" : { "createDate" : -1 } },
{
"$group" : {
"_id" : "$from",
"from" : { "$first" : "$from" },
"to" : { "$first" : "$to" },
"content" : { "$first" : "$content" },
"createDate" : { "$first" : "$createDate" }
}
}
])
您可以在此處使用累加器。 最大蓄能器將組from
再取最大值createdDate
,將返回最新的。
db.messages.aggregate([
{"$match":{}},
{"$group":{
"_id":"$from",
"createdDate":{"$max":"$createdDate"},
"content" : "$content"
}
},
{"$sort":{"createdDate":-1}},{"$skip":0},{"$limit":10}],{})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.