我有像
这样的文件[{"_id" : "12","name" : "test1", "nesArray" : [1,2], "createdAt" : ISODate("2016-10-15T06:17:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,3], "createdAt" :ISODate("2016-10-15T06:17:54.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,4], "createdAt" :ISODate("2016-10-15T06:17:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,2], "createdAt" :ISODate("2016-10-15T06:18:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,3], "createdAt" :ISODate("2016-10-15T06:18:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,2],"createdAt" :ISODate("2016-10-15T06:19:53.946Z") } ]
我想只检索那些有
的文档结果应该是
[{"_id" : "12","name" : "test1", "nesArray" : [1,4], "createdAt" :ISODate("2016-10-15T06:17:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,3], "createdAt" :ISODate("2016-10-15T06:18:53.946Z") },
{"_id" : "12","name" : "test1", "nesArray" : [1,2],"createdAt" :ISODate("2016-10-15T06:19:53.946Z") }]
我尝试使用聚合但我不想使用聚合(Mongoose populate不能用于聚合)。
答案 0 :(得分:0)
这基本上就是你尝试过的,但是使用$last
获取所有字段并在之后投影具有与DB中相同的结构:
db.coll.aggregate(
{
$sort: { createdAt: 1 }
},
{
$group: {
_id: "$nesArray",
id: { $last: "$_id" },
name: {$last: "$name"},
createdAt: { $last: "$createdAt"}
}
},
{
$project: {
_id: "$id",
nesArray: "$_id",
name: 1,
createdAt: 1
}
}
)