我是MongoDb世界的新手。我有以下情况:
具有以下数据的销售集合:
db.sales.insert({ "_id" : 1, "item" : "abc", "date" : ISODate("2014-01-01T08:00:00.0Z"), "price" : 10, "quantity" : 20 })
db.sales.insert({ "_id" : 2, "item" : "jkl", "date" : ISODate("2014-02-03T09:00:00.0Z"), "price" : 20, "quantity" : 1 })
db.sales.insert({ "_id" : 3, "item" : "xyz", "date" : ISODate("2014-02-03T09:05:00.0Z"), "price" : 5, "quantity" : 5 })
db.sales.insert({ "_id" : 4, "item" : "abc", "date" : ISODate("2014-02-15T08:00:00.0Z"), "price" : 10, "quantity" : 10 })
db.sales.insert({ "_id" : 5, "item" : "xyz", "date" : ISODate("2014-02-15T09:05:00.0Z"), "price" : 5, "quantity" : 10 })
db.sales.insert({ "_id" : 6, "item" : "xyz", "date" : ISODate("2014-02-15T12:05:10.0Z"), "price" : 5, "quantity" : 5 })
db.sales.insert({ "_id" : 7, "item" : "xyz", "date" : ISODate("2014-02-15T14:12:12.0Z"), "price" : 5, "quantity" : 10 })
db.sales.insert({ "_id" : 8, "item" : "abc", "date" : ISODate("2014-02-10T08:00:00.0Z"), "price" : 10, "quantity" : 30 })
我想为每个项目选择最近的销售(整个文档)。
预期结果:
[
{ "_id" : 2, "item" : "jkl", "date" : "2014-02-03T09:00:00Z", "price" : 20, "quantity" : 1 },
{ "_id" : 4, "item" : "abc", "date" : "2014-02-15T08:00:00Z", "price" : 10, "quantity" : 10 },
{ "_id" : 7, "item" : "xyz", "date" : "2014-02-15T14:12:12Z", "price" : 5, "quantity" : 10 }
]
我一直在寻找,但是找不到能够检索每个类别的最新整个文档的解决方案。
我尝试了以下操作,但是我只得到_id和lastSalesDate。
db.sales.aggregate(
[
{ $sort: { item: 1, date: 1 } },
{
$group:
{
_id: "$item",
lastSalesDate: { $last: "$date" }
}
}
]
)
如何检索所有字段?
我在使用MongoDB驱动程序和scala应用程序,需要检索预期结果。但是,也欢迎使用MongoDB查询格式的任何解决方案。
谢谢!
答案 0 :(得分:2)
尝试此查询,
db.sales.aggregate([
// Sort by date (Use -1 to sort in descending order to get most recent date)
{ $sort: { date: -1 } },
// Group by Item and Store First Sorted Whole Document in itemObj
{ $group: { _id: "$item", itemObj : { $first: "$$ROOT" }} },
// Replace the Document with itemObj Object
{ $replaceRoot: { newRoot: "$itemObj"} }
])