鉴于一系列“购买”,我如何才能获得每个人的最近购买?
每个人在first_name
和last_name
上都是唯一的。
示例收集:
[
{
first_name: "Don",
last_name: "Foobar",
date: 11111111, // The unix timestamp of purchase
purchase: {...}
},
{
first_name: "Don",
last_name: "Foobar",
date: 22222222,
purchase: {...}
},
{
first_name: "James",
last_name: "McManason",
date: 12341234,
purchase: {...}
}
...
]
我尝试了什么:
下面的代码可以工作(超级次优),给出一组人名来迭代:
collection
.find({ first_name: "Tom", last_name: "Brady" })
.sort({ date: -1 })
.limit(1)
collection
.find({ first_name: "James", last_name: "Foo" })
.sort({ date: -1 })
.limit(1)
collection
.find({ first_name: "Marcia", last_name: "Bar" })
.sort({ date: -1 })
.limit(1)
答案 0 :(得分:1)
那么您需要更通用的解决方案吗?如果是这样,那就试试吧:
db.collection.aggregate([
{ $sort: { date: -1}}, // sort by date descending
{
$group: {
_id: { firstName: "$first_name", lastName: "$last_name"}, // group by
// first and last name
purchase: {$first: "$purchase"} // get the first purchase since the documents are
// ordered by date and the first is also the latest
}
}
])
对整个集合进行排序虽然效率不高,但您应该考虑在$match
之前添加$sort
。