我有一组MongoDB文档,如下所示:
{
"_id" : "123",
"created_by": "bob",
"date_added": ISODate("2014-08-27T17:43:23Z"),
"size": "XL",
"color": "red"
}
我想回答的问题是:每个人最近添加的项目的颜色是什么?
我已经走到这一步了:
db.stuff.aggregate([
{ $group: { _id: { who: "$created_by"}, added: { $max: "$date_added" } } },
])
{ "_id" : { "who" : "bob" }, "added" : ISODate("2014-09-30T07:06:38.135Z") }
{ "_id" : { "who" : "mike" }, "added" : ISODate("2014-09-30T07:10:03.098Z") }
{ "_id" : { "who" : "mary" }, "added" : ISODate("2014-09-30T07:07:27.787Z") }
{ "_id" : { "who" : "john" }, "added" : ISODate("2014-09-30T07:09:51.418Z") }
但是,它仅返回用户的名称和添加文档的日期。我无法弄清楚如何让查询也返回颜色。谢谢!
答案 0 :(得分:1)
我认为这对你有用。
db.stuff.aggregate([ {
$sort : {
date_added : -1
}
}, {
$group : {
_id : {
who : "$created_by"
},
added : {
$first : "$date_added"
},
color : {
$first : "$color"
}
}
} ]);