我想提取整个文档进行分组。
例如,我有一个名为“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" } } }
]
当然,这只返回两个字段,即 updatedAt
和 commentId
。
现在如果我想要整个文档怎么办。我将不得不单独编写每个字段,但我不想这样做。
首选方法应该是什么?
编辑:简单查询
收藏=
[
{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' }
]
最佳答案
您可以使用 $$ROOT
聚合中的系统变量以引用管道中该阶段的完整顶级文档:
mongoose.model('sub_comment').aggregate([
{ $sort: { commentId : 1, updatedAt: -1 } },
{ $group: { _id: "$commentId", doc: { $first: "$$ROOT" } } }
]
关于mongodb - 在 mongodb 集合中查找所有按字段最新且与另一个字段不同的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33170253/