我有一个包含对象(事件记录)的集合,如下所示:
{_id: 1, type: "A", val2: "x", val3: "z", date: 1/1}
{_id: 2, type: "A", val2: "y", val3: "y", date: 2/1}
{_id: 3, type: "C", val2: "z", val3: "x", date: 3/1}
{_id: 4, type: "B", val2: "x", val3: "z", date: 4/1}
{_id: 5, type: "C", val2: "y", val3: "y", date: 5/1}
{_id: 6, type: "B", val2: "z", val3: "x", date: 6/1}
我想获取完整对象以获取每种类型的最新日期,因此在上面的示例中,它应该返回带有ID的记录:2,5,6
我正在做这样的管道查询:
db.items.aggregate(
[
{
$group:
{
_id: "$type",
lastDate: { $last: "$date" }
}
}
]
)
但这只返回我这样的文件:
{ _id: 2, lastDate: 2/1}
我希望整个对象(使用val2,val3等)
我该如何做到这一点?
由于
答案 0 :(得分:1)
您只能针对特定项目执行此操作
db.items.aggregate(
[
{
$group:
{
_id: "$type",
lastDate: { $last: "$date" },
val2: { $last: "$val2" },
val3: { $last: "$val3" }
}
}
]
)
请注意,您应使用ISODate
作为日期和时间字段的类型。
答案 1 :(得分:1)
根据 Markus W Mahlberg 首先回答您应该将date
类型更改为ISODate
或timestamp
,然后使用聚合。首先排序date
和组然后像下面的查询
db.collectionName.aggregate({"$sort":{"date":-1}},
{"$group":{"_id":"$type","lastDate":{"$first":"$date"},
"val2":{"$first":"$val2"},"val3":{"$first":"$val3"}}})