Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在Mongodb中聚合不同的数组字段_Node.js_Database_Mongodb_Mongoose_Nosql - Fatal编程技术网

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
    按创建日期排序
  • $group
    按用户数组并在latestDoc中获取最新文档
  • $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" }
])