Return latest 2 entries from a mongo database?How to get the last N records in mongodb?Ways to implement data versioning in MongoDBHow do I drop a MongoDB database from the command line?How to list all collections in the mongo shell?Mongo DB shell, how to count duplicate entries in a collectionManually deleting connect-mongo session by _id cast errorMgo (mongo for go) support for materialized paths?MongoDB BSON OID FailureGet a document with a specific _id with mongo-delphi-driverMongo/Mongoose Sorting funkyClearing mongoDB collection with php, doesn't seem to work permanently

Who is the controller of a Pacifism enchanting my creature?

Unconventional examples of mathematical modelling

When was "Fredo" an insult to Italian-Americans?

What is the prop for Thor's hammer (Mjölnir) made of?

Why are electric shavers specifically permitted under FAR §91.21

Are there really no countries that protect Freedom of Speech as the United States does?

Why does Japan use the same type of AC power outlet as the US?

What's the relationship betweeen MS-DOS and XENIX?

What if a restaurant suddenly cannot accept credit cards, and the customer has no cash?

What evidence points to a long ō in the first syllable of nōscō's present-tense form?

Attacking the Hydra

The more + the + comparative degree

Setting up a Mathematical Institute of Refereeing?

A+ rating still unsecure by Google Chrome's opinion

A man in the desert is bitten by a skeletal animal, its skull gets stuck on his arm

Airline power sockets shut down when I plug my computer in. How can I avoid that?

Can anybody tell me who this Pokemon is?

Scam? Phone call from "Department of Social Security" asking me to call back

Is this bar slide trick shown on Cheers real or a visual effect?

How to measure if Scrum Master is making a difference and when to give up

Help, I cannot decide when to start the story

Is there a name for the technique in songs/poems, where the rhyming pattern primes the listener for a certain line, which never comes?

Is there a fallacy about "appeal to 'big words'"?

How can I find an old paper when the usual methods fail?



Return latest 2 entries from a mongo database?


How to get the last N records in mongodb?Ways to implement data versioning in MongoDBHow do I drop a MongoDB database from the command line?How to list all collections in the mongo shell?Mongo DB shell, how to count duplicate entries in a collectionManually deleting connect-mongo session by _id cast errorMgo (mongo for go) support for materialized paths?MongoDB BSON OID FailureGet a document with a specific _id with mongo-delphi-driverMongo/Mongoose Sorting funkyClearing mongoDB collection with php, doesn't seem to work permanently






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have a database recording the unix time, latitude and longitude of a received message from a GPS unit. I need a way to select the latest two entries from this database to work with in php.



Example database entry:
[3] => stdClass Object ( [_id] => MongoDBBSONObjectId Object ( [oid] => 5c7fe3fc1c37210bf96e8182 ) [Latitude] => 53.385360717773 [Longitude] => -6.6032276153564 [Time] => 1551885285 ) )



So far I only needed one and I got it by searching for the largest timestamp. Is there a way to simply return the latest two entries in mongo like in mySQL? I've noticed 'limit' returns the first entries not the last:



 $options=['limit' => 2];
$filter=[];
//$cursor = $collection->find($filter, $options);
$cursor = $collection->find($filter);
$largest = 0;
foreach($cursor as $document){
if ($largest < $document["Time"])
$largest = $document["Time"];
$longitude = $document["Longitude"];
$latitude = $document["Latitude"];



Thanks for any help.



edit: I've found this question How to get the last N records in mongodb?. The mongo version is different but the principle seems sound: use 'sort' then 'limit'. The syntax is quite different thought how could I combine the two in this version?



"db.foo.find().sort(_id:1).limit(50);"



 $options=['limit' => 2];
$filter=[];
$cursor = $collection->find($filter, $options);









share|improve this question
































    0















    I have a database recording the unix time, latitude and longitude of a received message from a GPS unit. I need a way to select the latest two entries from this database to work with in php.



    Example database entry:
    [3] => stdClass Object ( [_id] => MongoDBBSONObjectId Object ( [oid] => 5c7fe3fc1c37210bf96e8182 ) [Latitude] => 53.385360717773 [Longitude] => -6.6032276153564 [Time] => 1551885285 ) )



    So far I only needed one and I got it by searching for the largest timestamp. Is there a way to simply return the latest two entries in mongo like in mySQL? I've noticed 'limit' returns the first entries not the last:



     $options=['limit' => 2];
    $filter=[];
    //$cursor = $collection->find($filter, $options);
    $cursor = $collection->find($filter);
    $largest = 0;
    foreach($cursor as $document){
    if ($largest < $document["Time"])
    $largest = $document["Time"];
    $longitude = $document["Longitude"];
    $latitude = $document["Latitude"];



    Thanks for any help.



    edit: I've found this question How to get the last N records in mongodb?. The mongo version is different but the principle seems sound: use 'sort' then 'limit'. The syntax is quite different thought how could I combine the two in this version?



    "db.foo.find().sort(_id:1).limit(50);"



     $options=['limit' => 2];
    $filter=[];
    $cursor = $collection->find($filter, $options);









    share|improve this question




























      0












      0








      0








      I have a database recording the unix time, latitude and longitude of a received message from a GPS unit. I need a way to select the latest two entries from this database to work with in php.



      Example database entry:
      [3] => stdClass Object ( [_id] => MongoDBBSONObjectId Object ( [oid] => 5c7fe3fc1c37210bf96e8182 ) [Latitude] => 53.385360717773 [Longitude] => -6.6032276153564 [Time] => 1551885285 ) )



      So far I only needed one and I got it by searching for the largest timestamp. Is there a way to simply return the latest two entries in mongo like in mySQL? I've noticed 'limit' returns the first entries not the last:



       $options=['limit' => 2];
      $filter=[];
      //$cursor = $collection->find($filter, $options);
      $cursor = $collection->find($filter);
      $largest = 0;
      foreach($cursor as $document){
      if ($largest < $document["Time"])
      $largest = $document["Time"];
      $longitude = $document["Longitude"];
      $latitude = $document["Latitude"];



      Thanks for any help.



      edit: I've found this question How to get the last N records in mongodb?. The mongo version is different but the principle seems sound: use 'sort' then 'limit'. The syntax is quite different thought how could I combine the two in this version?



      "db.foo.find().sort(_id:1).limit(50);"



       $options=['limit' => 2];
      $filter=[];
      $cursor = $collection->find($filter, $options);









      share|improve this question
















      I have a database recording the unix time, latitude and longitude of a received message from a GPS unit. I need a way to select the latest two entries from this database to work with in php.



      Example database entry:
      [3] => stdClass Object ( [_id] => MongoDBBSONObjectId Object ( [oid] => 5c7fe3fc1c37210bf96e8182 ) [Latitude] => 53.385360717773 [Longitude] => -6.6032276153564 [Time] => 1551885285 ) )



      So far I only needed one and I got it by searching for the largest timestamp. Is there a way to simply return the latest two entries in mongo like in mySQL? I've noticed 'limit' returns the first entries not the last:



       $options=['limit' => 2];
      $filter=[];
      //$cursor = $collection->find($filter, $options);
      $cursor = $collection->find($filter);
      $largest = 0;
      foreach($cursor as $document){
      if ($largest < $document["Time"])
      $largest = $document["Time"];
      $longitude = $document["Longitude"];
      $latitude = $document["Latitude"];



      Thanks for any help.



      edit: I've found this question How to get the last N records in mongodb?. The mongo version is different but the principle seems sound: use 'sort' then 'limit'. The syntax is quite different thought how could I combine the two in this version?



      "db.foo.find().sort(_id:1).limit(50);"



       $options=['limit' => 2];
      $filter=[];
      $cursor = $collection->find($filter, $options);






      mongodb






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 27 at 12:06







      Jay.F

















      asked Mar 27 at 11:53









      Jay.FJay.F

      418 bronze badges




      418 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          1














          Keep extending the query as follows:



          $cursor = $collection->find($filter)->sort(array('_id'=>-1))->limit(2)





          share|improve this answer

























          • Caused an error, I don't think this is compatible with my version. Figured it it thought thanks for your help!

            – Jay.F
            Mar 27 at 12:22


















          0














          Got it to work with:



           $options = ['sort' => ['Time' => -1], 'limit' => 2];
          $filter=[];
          $cursor = $collection->find($filter, $options);





          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%2f55376570%2freturn-latest-2-entries-from-a-mongo-database%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Keep extending the query as follows:



            $cursor = $collection->find($filter)->sort(array('_id'=>-1))->limit(2)





            share|improve this answer

























            • Caused an error, I don't think this is compatible with my version. Figured it it thought thanks for your help!

              – Jay.F
              Mar 27 at 12:22















            1














            Keep extending the query as follows:



            $cursor = $collection->find($filter)->sort(array('_id'=>-1))->limit(2)





            share|improve this answer

























            • Caused an error, I don't think this is compatible with my version. Figured it it thought thanks for your help!

              – Jay.F
              Mar 27 at 12:22













            1












            1








            1







            Keep extending the query as follows:



            $cursor = $collection->find($filter)->sort(array('_id'=>-1))->limit(2)





            share|improve this answer













            Keep extending the query as follows:



            $cursor = $collection->find($filter)->sort(array('_id'=>-1))->limit(2)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Mar 27 at 12:10









            Anirudh SimhaAnirudh Simha

            2497 bronze badges




            2497 bronze badges















            • Caused an error, I don't think this is compatible with my version. Figured it it thought thanks for your help!

              – Jay.F
              Mar 27 at 12:22

















            • Caused an error, I don't think this is compatible with my version. Figured it it thought thanks for your help!

              – Jay.F
              Mar 27 at 12:22
















            Caused an error, I don't think this is compatible with my version. Figured it it thought thanks for your help!

            – Jay.F
            Mar 27 at 12:22





            Caused an error, I don't think this is compatible with my version. Figured it it thought thanks for your help!

            – Jay.F
            Mar 27 at 12:22













            0














            Got it to work with:



             $options = ['sort' => ['Time' => -1], 'limit' => 2];
            $filter=[];
            $cursor = $collection->find($filter, $options);





            share|improve this answer





























              0














              Got it to work with:



               $options = ['sort' => ['Time' => -1], 'limit' => 2];
              $filter=[];
              $cursor = $collection->find($filter, $options);





              share|improve this answer



























                0












                0








                0







                Got it to work with:



                 $options = ['sort' => ['Time' => -1], 'limit' => 2];
                $filter=[];
                $cursor = $collection->find($filter, $options);





                share|improve this answer













                Got it to work with:



                 $options = ['sort' => ['Time' => -1], 'limit' => 2];
                $filter=[];
                $cursor = $collection->find($filter, $options);






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 27 at 12:21









                Jay.FJay.F

                418 bronze badges




                418 bronze badges






























                    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%2f55376570%2freturn-latest-2-entries-from-a-mongo-database%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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    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

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현