Node.js 如何在Mongodb中聚合不同的数组字段
我有这个模式Node.js 如何在Mongodb中聚合不同的数组字段,node.js,database,mongodb,mongoose,nosql,Node.js,Database,Mongodb,Mongoose,Nosql,我有这个模式 const GroupSchema = new Schema({ id: { type: String }, users: [{ type: Number }], status: { type: Boolean } }, { timestamps: true }); 我尝试聚合按创建日期排序的不同用户值。 范例 我尝试: Group.aggregate([ { "$sort": { "createdAt&q
const GroupSchema = new Schema({
id: { type: String },
users: [{ type: Number }],
status: { type: Boolean }
},
{
timestamps: true
});
我尝试聚合按创建日期排序的不同用户值。
范例
我尝试:
Group.aggregate([
{ "$sort": { "createdAt": -1 } },
{ $group : { _id : "$users" }}, //, created : { $last : "created" }
{ $match : { users : {$in : [1111] } }}
])
我想
{
"users": [1111, 2222],
"createdAt": {
"$date": "2020-09-30T10:51:33.058Z"
}
}
我怎样才能解决这个问题?
谢谢。你可以试试
您的条件$match
按创建日期排序$sort
按用户数组并在latestDoc中获取最新文档$group
替换根目录中最新的文档$replaceWith
请添加您的预期结果。我想按不同的用户字段进行筛选,在此示例数据中,我希望对象具有高数据2020-09-30T10:51 Ok,但如果您根据文档添加您的预期结果会更好。Ok,我更新问题。看起来很完美。我深化了文档,谢谢。
{
"users": [1111, 2222],
"createdAt": {
"$date": "2020-09-30T10:51:33.058Z"
}
}
db.collection.aggregate([
{ $match: { users: { $in: [1111] } } },
{ $sort: { createdAt: -1 } },
{
$group: {
_id: "$users",
latestDoc: { $first: "$$ROOT" }
}
},
{ $replaceWith: "$latestDoc" }
])