Return all fields MongoDB Aggregate

前端 未结 1 1267
甜味超标
甜味超标 2021-01-22 06:23

I tried searching on here but couldn\'t really find what I need. I have documents like this:

{
    appletype:Granny,
    color:Green,
    datePicked:2015-01-26,
         


        
相关标签:
1条回答
  • 2021-01-22 06:56

    From your description, it sounds like you want one document for each of the types of apple in your collection and showing the document with the most recent datePicked value.

    Here is an aggregate query for that:

    db.collection.aggregate([
      { $sort: { "datePicked": -1 },
      { $group: { _id: "$appletype", color: { $first: "$color" }, datePicked: { $first: "$datePicked" }, dateRipe: { $first: "$dateRipe" }, numPicked: { $first: "$numPicked" } } },
      { $project: { _id: 0, color: 1, datePicked: 1, dateRipe: 1, numPicked: 1, appletype: "$_id" } }
    ])
    

    But then based on the aggregate query you've written, it looks like you're trying to get this:

    db.collection.find({appletype: "Granny"}).sort({datePicked: -1}).limit(1);
    
    0 讨论(0)
提交回复
热议问题