查找字段中最新的所有文档,并且与mongodb集合中的另一个字段不同

时间:2015-10-16 12:13:35

标签: mongodb mongoose

我想将整个文档提取到组中。

例如,我有一个名为“sub_comment”的集合。

每个“sub_comment”都将“comment”中的一个引用为“commentId”。

sub_comment = new Schema({  // as per mongoose schema
   updatedAt : Date,
   text : String,
   by : String,
   info : String,
   commentId : { type : ObjectId, ref : 'commment' }
})

现在我想提取所有那些最新的子评论(完整文档)(通过“updatedAt”)按每个评论分组。

我目前正在这样做:

mongoose.model('sub_comment').aggregate([
            { $sort: { commentId : 1, updatedAt: -1 } },
            { $group: { _id: "$commentId", updatedAt: { $first: "$updatedAt" } } }
          ]

当然,这只返回updatedAtcommentId两个字段。

现在如果我想要整个文件怎么办?我将不得不分别编写每个字段,我不想这样做。

什么应该是首选方法?

编辑:简单查询

collection =

[
{commentId : 1, updatedAt : ISO("2015-10-13T11:38:29.000Z"), xyz  : 'xyz1' },
{commentId : 2, updatedAt : ISO("2015-10-10T11:38:29.000Z"), xyz  : 'xyz2'  },
{commentId : 2, updatedAt : ISO("2015-10-14T11:38:29.000Z"), xyz  : 'xyz3'  },
{commentId : 1, updatedAt : ISO("2015-10-11T11:38:29.000Z"), xyz  : 'xyz4'  }
]

我想要输出:

[
{commentId : 1, updatedAt : ISO("2015-10-13T11:38:29.000Z"), 'xyz' : 'xyz1' },
{commentId : 2, updatedAt : ISO("2015-10-14T11:38:29.000Z"), 'xyz' : 'xyz3'  }
]

1 个答案:

答案 0 :(得分:3)

您可以在聚合中使用$$ROOT系统变量来引用管道中该阶段的完整顶级文档:

mongoose.model('sub_comment').aggregate([
        { $sort: { commentId : 1, updatedAt: -1 } },
        { $group: { _id: "$commentId", doc: { $first: "$$ROOT" } } }
      ]