MongoDB get full doc after match, group, and sortMongoDb/PHP, can't get grouping to work right with aggregate frameworkMongoDB - sort by subdocument matchTrouble using $group twice in mongodb aggregation queryGetting a complete object via $max in mongodb aggregationMongoDB aggregation pipeline $match orderMongoDB Aggregation Count of Group By Inner ArrayMongodb: Multi _id aggregate group not using indexWhy sort is affecting match to use indexes on MongoDB 3.0?MongoDB - Grouping by a substringMongoDB - Query - Top Document per Group

In Endgame, why were these characters still around?

Upside-Down Pyramid Addition...REVERSED!

Do I really need diodes to receive MIDI?

What are the spoon bit of a spoon and fork bit of a fork called?

Is induction neccessary for proving that every injective mapping of a finite set into itself is a mapping onto itself?

Can Ghost kill White Walkers or Wights?

Should I replace my bicycle tires if they have not been inflated in multiple years

How do I tell my manager that his code review comment is wrong?

Where can I go to avoid planes overhead?

FindInstance and cosine system of equations

Father and Son and Grandsons

Is a lifestealing melee cantrip, in the form of booming blade, unbalanced?

What is the minimal installation possible in order to run a .jar Java file?

What happens if I start too many background jobs?

Besides the up and down quark, what other quarks are present in daily matter around us?

Selecting a secure PIN for building access

Sed Usage to update GRUB file

Theorem won't go to multiple lines and is causing text to run off the page

Is Jon mad at Ghost for some reason and is that why he won't acknowledge him?

If prion is a protein. Why is it not disassembled by the digestive system?

Has any spacecraft ever had the ability to directly communicate with civilian air traffic control?

I caught several of my students plagiarizing. Could it be my fault as a teacher?

A non-technological, repeating, phenomenon in the sky, holding its position in the sky for hours

In a vacuum triode, what prevents the grid from acting as another anode?



MongoDB get full doc after match, group, and sort


MongoDb/PHP, can't get grouping to work right with aggregate frameworkMongoDB - sort by subdocument matchTrouble using $group twice in mongodb aggregation queryGetting a complete object via $max in mongodb aggregationMongoDB aggregation pipeline $match orderMongoDB Aggregation Count of Group By Inner ArrayMongodb: Multi _id aggregate group not using indexWhy sort is affecting match to use indexes on MongoDB 3.0?MongoDB - Grouping by a substringMongoDB - Query - Top Document per Group






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















Order:




order_id: 1,
order_time: ISODate(...),
customer_id: 456,
products: [

product_id: 1,
product_name: "Pencil"
,

product_id: 2,
product_name: "Scissors"
,

product_id: 3,
product_name: "Tape"

]



I have a collection with a whole bunch of documents like the above. I would like to query for the latest order for each customer who ordered Scissors.



That is, where there exists a "products.product_name" which equals "Scissors", group by customer_id, give me the full document where the "order_time" is the "max" for that group.



To find the documents, I could do like find( 'products.product_name' : "Scissors" ) but then I get all of the order with Scissors, I only want the most recent.



So, I am looking at aggregation... Mongo's "$group" aggregation stage seems to require that you do some kind of actual aggregation inside like sum or max or whatever. I am guessing there's some combination of $match, $group, and $sort to use here but I can't seem to quite get it working.



Something close:



db.storcap.aggregate(
[

$match: 'products.product_name' : "Scissors"
,

$sort: created_at:-1
,

$group:
_id: "$customer_id",

]
)


But this doesn't return the full doc and I am not sure that it's doing the sorting and grouping right.










share|improve this question




























    1















    Order:




    order_id: 1,
    order_time: ISODate(...),
    customer_id: 456,
    products: [

    product_id: 1,
    product_name: "Pencil"
    ,

    product_id: 2,
    product_name: "Scissors"
    ,

    product_id: 3,
    product_name: "Tape"

    ]



    I have a collection with a whole bunch of documents like the above. I would like to query for the latest order for each customer who ordered Scissors.



    That is, where there exists a "products.product_name" which equals "Scissors", group by customer_id, give me the full document where the "order_time" is the "max" for that group.



    To find the documents, I could do like find( 'products.product_name' : "Scissors" ) but then I get all of the order with Scissors, I only want the most recent.



    So, I am looking at aggregation... Mongo's "$group" aggregation stage seems to require that you do some kind of actual aggregation inside like sum or max or whatever. I am guessing there's some combination of $match, $group, and $sort to use here but I can't seem to quite get it working.



    Something close:



    db.storcap.aggregate(
    [

    $match: 'products.product_name' : "Scissors"
    ,

    $sort: created_at:-1
    ,

    $group:
    _id: "$customer_id",

    ]
    )


    But this doesn't return the full doc and I am not sure that it's doing the sorting and grouping right.










    share|improve this question
























      1












      1








      1








      Order:




      order_id: 1,
      order_time: ISODate(...),
      customer_id: 456,
      products: [

      product_id: 1,
      product_name: "Pencil"
      ,

      product_id: 2,
      product_name: "Scissors"
      ,

      product_id: 3,
      product_name: "Tape"

      ]



      I have a collection with a whole bunch of documents like the above. I would like to query for the latest order for each customer who ordered Scissors.



      That is, where there exists a "products.product_name" which equals "Scissors", group by customer_id, give me the full document where the "order_time" is the "max" for that group.



      To find the documents, I could do like find( 'products.product_name' : "Scissors" ) but then I get all of the order with Scissors, I only want the most recent.



      So, I am looking at aggregation... Mongo's "$group" aggregation stage seems to require that you do some kind of actual aggregation inside like sum or max or whatever. I am guessing there's some combination of $match, $group, and $sort to use here but I can't seem to quite get it working.



      Something close:



      db.storcap.aggregate(
      [

      $match: 'products.product_name' : "Scissors"
      ,

      $sort: created_at:-1
      ,

      $group:
      _id: "$customer_id",

      ]
      )


      But this doesn't return the full doc and I am not sure that it's doing the sorting and grouping right.










      share|improve this question














      Order:




      order_id: 1,
      order_time: ISODate(...),
      customer_id: 456,
      products: [

      product_id: 1,
      product_name: "Pencil"
      ,

      product_id: 2,
      product_name: "Scissors"
      ,

      product_id: 3,
      product_name: "Tape"

      ]



      I have a collection with a whole bunch of documents like the above. I would like to query for the latest order for each customer who ordered Scissors.



      That is, where there exists a "products.product_name" which equals "Scissors", group by customer_id, give me the full document where the "order_time" is the "max" for that group.



      To find the documents, I could do like find( 'products.product_name' : "Scissors" ) but then I get all of the order with Scissors, I only want the most recent.



      So, I am looking at aggregation... Mongo's "$group" aggregation stage seems to require that you do some kind of actual aggregation inside like sum or max or whatever. I am guessing there's some combination of $match, $group, and $sort to use here but I can't seem to quite get it working.



      Something close:



      db.storcap.aggregate(
      [

      $match: 'products.product_name' : "Scissors"
      ,

      $sort: created_at:-1
      ,

      $group:
      _id: "$customer_id",

      ]
      )


      But this doesn't return the full doc and I am not sure that it's doing the sorting and grouping right.







      mongodb aggregation-framework






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 22 at 21:03









      MichaelBMichaelB

      553720




      553720






















          1 Answer
          1






          active

          oldest

          votes


















          1














          You can use $first operator to get most recent order (are ordered desc) and special variable $$ROOT to get whole object in a final result:



          db.storcap.aggregate([

          $match: 'products.product_name' : "Scissors"
          ,

          $sort: created_at:-1
          ,

          $group:
          _id: "$customer_id",
          lastOrder: $first: "$$ROOT"


          ])





          share|improve this answer























            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%2f55307742%2fmongodb-get-full-doc-after-match-group-and-sort%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 $first operator to get most recent order (are ordered desc) and special variable $$ROOT to get whole object in a final result:



            db.storcap.aggregate([

            $match: 'products.product_name' : "Scissors"
            ,

            $sort: created_at:-1
            ,

            $group:
            _id: "$customer_id",
            lastOrder: $first: "$$ROOT"


            ])





            share|improve this answer



























              1














              You can use $first operator to get most recent order (are ordered desc) and special variable $$ROOT to get whole object in a final result:



              db.storcap.aggregate([

              $match: 'products.product_name' : "Scissors"
              ,

              $sort: created_at:-1
              ,

              $group:
              _id: "$customer_id",
              lastOrder: $first: "$$ROOT"


              ])





              share|improve this answer

























                1












                1








                1







                You can use $first operator to get most recent order (are ordered desc) and special variable $$ROOT to get whole object in a final result:



                db.storcap.aggregate([

                $match: 'products.product_name' : "Scissors"
                ,

                $sort: created_at:-1
                ,

                $group:
                _id: "$customer_id",
                lastOrder: $first: "$$ROOT"


                ])





                share|improve this answer













                You can use $first operator to get most recent order (are ordered desc) and special variable $$ROOT to get whole object in a final result:



                db.storcap.aggregate([

                $match: 'products.product_name' : "Scissors"
                ,

                $sort: created_at:-1
                ,

                $group:
                _id: "$customer_id",
                lastOrder: $first: "$$ROOT"


                ])






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 22 at 21:07









                micklmickl

                16.8k61841




                16.8k61841





























                    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%2f55307742%2fmongodb-get-full-doc-after-match-group-and-sort%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







                    Popular posts from this blog

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해