【问题标题】:MongoDB: Latest record for Each category by TimestampMongoDB:按时间戳划分的每个类别的最新记录
【发布时间】:2020-06-18 00:48:37
【问题描述】:

我是 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 查询格式的解决方案。

谢谢!

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    试试这个查询,

    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"} }  
    ])
    

    【讨论】:

    • 嗨@Mohammad,非常感谢,这给出了预期的结果。我会用 MongoDb 的 scala 驱动程序来试试这个。
    猜你喜欢
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    相关资源
    最近更新 更多