【发布时间】:2015-10-16 21:21:18
【问题描述】:
我想将整个文档提取到组中。
例如,我有一个名为“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' }
]
【问题讨论】: