鉴于此源数据:
{ "_id" : ObjectId("1"), "productID" : 1, "amount" : 1, "date" : ISODate("2017-02-01T00:00:00Z") }
{ "_id" : ObjectId("2"), "productID" : 2, "amount" : 2, "date" : ISODate("2017-02-01T00:00:00Z") }
{ "_id" : ObjectId("3"), "productID" : 3, "amount" : 3, "date" : ISODate("2017-02-01T00:00:00Z") }
{ "_id" : ObjectId("4"), "productID" : 4, "amount" : 4, "date" : ISODate("2017-02-01T00:00:00Z") }
{ "_id" : ObjectId("5"), "productID" : 1, "amount" : 11, "date" : ISODate("2017-02-02T00:00:00Z") }
{ "_id" : ObjectId("6"), "productID" : 2, "amount" : 22, "date" : ISODate("2017-02-02T00:00:00Z") }
{ "_id" : ObjectId("7"), "productID" : 2, "amount" : 222, "date" : ISODate("2017-02-03T00:00:00Z") }
{ "_id" : ObjectId("8"), "productID" : 3, "amount" : 33, "date" : ISODate("2017-02-03T00:00:00Z") }
我想获取每个产品的最新记录(键入productID
)并打印出按productID
排序的每个产品的记录的完整行。所以我从上面得到的输出是:
{ "_id" : ObjectId("5"), "productID" : 1, "amount" : 11, "date" : ISODate("2017-02-02T00:00:00Z") }
{ "_id" : ObjectId("7"), "productID" : 2, "amount" : 222, "date" : ISODate("2017-02-03T00:00:00Z") }
{ "_id" : ObjectId("8"), "productID" : 3, "amount" : 33, "date" : ISODate("2017-02-03T00:00:00Z") }
{ "_id" : ObjectId("4"), "productID" : 4, "amount" : 4, "date" : ISODate("2017-02-01T00:00:00Z") }
我是Mongo的新手并且遇到问题,设法获得大部分内容但无法删除每个产品的其他旧记录。
答案 0 :(得分:2)
您可以使用$last和$first运算符。请注意,您应该在分组之前对文档进行排序:
db.so.aggregate([
{ $sort: {productID:-1, date: -1} },
{
$group: {
_id : "$productID",
date: {$last: "$date" },
amount: {$first: "$amount" },
id : {$first: "$_id"}
}
},
{ $project: { _id: "$id", productId: "$_id", date: 1, amount: 1 } }
])
输出:
{
"_id" : 5,
"productId" : 1,
"date" : ISODate("2017-02-01T00:00:00.000Z"),
"amount" : 11
},
{
"_id" : 7,
"productId" : 2,
"date" : ISODate("2017-02-01T00:00:00.000Z"),
"amount" : 222
},
{
"_id" : 8,
"productId" : 3,
"date" : ISODate("2017-02-01T00:00:00.000Z"),
"amount" : 33
},
{
"_id" : 4,
"productId" : 4,
"date" : ISODate("2017-02-01T00:00:00.000Z"),
"amount" : 4
}