问题描述
我有这个模式
const GroupSchema = new Schema({
id: { type: String },users: [{ type: Number }],status: { type: Boolean }
},{
timestamps: true
});
我尝试汇总按创建日期排序的不同用户值。 例子
{
"users": [1111,2222],"createdAt": {
"$date": "2020-09-30T10:51:33.058Z"
}
}
{
"users": [1111,"createdAt": {
"$date": "2020-09-29T10:51:33.058Z"
}
}
我尝试:
Group.aggregate([
{ "$sort": { "createdAt": -1 } },{ $group : { _id : "$users" }},//,created : { $last : "created" }
{ $match : { users : {$in : [1111] } }}
])
我希望
{
"users": [1111,"createdAt": {
"$date": "2020-09-30T10:51:33.058Z"
}
}
我该如何解决? 谢谢。
解决方法
您可以尝试
-
$match
您的情况 -
$sort
通过createdAt date -
$group
按用户排列,并在最新文档中获取最新文档 -
$replaceWith
替换root中的LatestDoc
db.collection.aggregate([
{ $match: { users: { $in: [1111] } } },{ $sort: { createdAt: -1 } },{
$group: {
_id: "$users",latestDoc: { $first: "$$ROOT" }
}
},{ $replaceWith: "$latestDoc" }
])