MongoDB Aggregate - Query to get most recent item in group










0















Given this source data:



 "_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")


I want to get the most recent record for each product (keyed on productID) and print out the full row for that record per product sorted on productID. So my desired output from above would be:



 "_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")


I'm new to Mongo and having problems, managed to get most of it but couldn't delete the other older records for each product.










share|improve this question




























    0















    Given this source data:



     "_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")


    I want to get the most recent record for each product (keyed on productID) and print out the full row for that record per product sorted on productID. So my desired output from above would be:



     "_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")


    I'm new to Mongo and having problems, managed to get most of it but couldn't delete the other older records for each product.










    share|improve this question


























      0












      0








      0








      Given this source data:



       "_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")


      I want to get the most recent record for each product (keyed on productID) and print out the full row for that record per product sorted on productID. So my desired output from above would be:



       "_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")


      I'm new to Mongo and having problems, managed to get most of it but couldn't delete the other older records for each product.










      share|improve this question
















      Given this source data:



       "_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")


      I want to get the most recent record for each product (keyed on productID) and print out the full row for that record per product sorted on productID. So my desired output from above would be:



       "_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")


      I'm new to Mongo and having problems, managed to get most of it but couldn't delete the other older records for each product.







      mongodb mongodb-query aggregation-framework






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 19 '17 at 10:36









      sazzad

      1,89461320




      1,89461320










      asked Feb 19 '17 at 9:23









      sub123sub123

      133




      133






















          1 Answer
          1






          active

          oldest

          votes


















          1














          You can use $last and $first operators. Note that you should sort documents before grouping:



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


          Output:




          "_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






          share|improve this answer

























          • Thanks that's a big help. One thing though - I am not aware of the full document schema in advance (ie this is generic)- so I know I will have a fixed date field and a id field (date, productID) but there will be many other fields that are undefined at runtime - how could I return all the fields from an object without specifying them.

            – sub123
            Feb 19 '17 at 21:03










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42325556%2fmongodb-aggregate-query-to-get-most-recent-item-in-group%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          You can use $last and $first operators. Note that you should sort documents before grouping:



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


          Output:




          "_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






          share|improve this answer

























          • Thanks that's a big help. One thing though - I am not aware of the full document schema in advance (ie this is generic)- so I know I will have a fixed date field and a id field (date, productID) but there will be many other fields that are undefined at runtime - how could I return all the fields from an object without specifying them.

            – sub123
            Feb 19 '17 at 21:03















          1














          You can use $last and $first operators. Note that you should sort documents before grouping:



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


          Output:




          "_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






          share|improve this answer

























          • Thanks that's a big help. One thing though - I am not aware of the full document schema in advance (ie this is generic)- so I know I will have a fixed date field and a id field (date, productID) but there will be many other fields that are undefined at runtime - how could I return all the fields from an object without specifying them.

            – sub123
            Feb 19 '17 at 21:03













          1












          1








          1







          You can use $last and $first operators. Note that you should sort documents before grouping:



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


          Output:




          "_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






          share|improve this answer















          You can use $last and $first operators. Note that you should sort documents before grouping:



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


          Output:




          "_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







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 19 '17 at 9:42

























          answered Feb 19 '17 at 9:36









          Sergey BerezovskiySergey Berezovskiy

          187k23315364




          187k23315364












          • Thanks that's a big help. One thing though - I am not aware of the full document schema in advance (ie this is generic)- so I know I will have a fixed date field and a id field (date, productID) but there will be many other fields that are undefined at runtime - how could I return all the fields from an object without specifying them.

            – sub123
            Feb 19 '17 at 21:03

















          • Thanks that's a big help. One thing though - I am not aware of the full document schema in advance (ie this is generic)- so I know I will have a fixed date field and a id field (date, productID) but there will be many other fields that are undefined at runtime - how could I return all the fields from an object without specifying them.

            – sub123
            Feb 19 '17 at 21:03
















          Thanks that's a big help. One thing though - I am not aware of the full document schema in advance (ie this is generic)- so I know I will have a fixed date field and a id field (date, productID) but there will be many other fields that are undefined at runtime - how could I return all the fields from an object without specifying them.

          – sub123
          Feb 19 '17 at 21:03





          Thanks that's a big help. One thing though - I am not aware of the full document schema in advance (ie this is generic)- so I know I will have a fixed date field and a id field (date, productID) but there will be many other fields that are undefined at runtime - how could I return all the fields from an object without specifying them.

          – sub123
          Feb 19 '17 at 21:03

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f42325556%2fmongodb-aggregate-query-to-get-most-recent-item-in-group%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          這個網誌中的熱門文章

          How to read a connectionString WITH PROVIDER in .NET Core?

          Node.js Script on GitHub Pages or Amazon S3

          Museum of Modern and Contemporary Art of Trento and Rovereto