Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb insert & sort

Hi I am trying to insert and sort data at the same time but it is not working. Have someone experience with it?

My example code looks like this:

  collection.insert({id:"224535353", type:postValue, date:new Date},  {safe:true},{$sort: { id: -1 }}, function(err, result){
                        console.log(result);

    });

Solution:

The mistake was I tried to sort the same id's.

collection.find({id:req.session.loggedIn},{sort:{date:-1}}).toArray(function(err, posts) { 

            console.log(posts);
});
like image 736
machu pichu Avatar asked Mar 15 '26 18:03

machu pichu


1 Answers

You sort on find not on insert. Basically you don't want to care how the data is stored and it's mongodbs problem to retrieve it sorted if you want it sorted so insert with

  collection.insert({id:"224535353", type:postValue, date:new Date},                      
                       {safe:true},function(err, result){console.log(result);});

and later find sorted with

collection.find({}).sort({id:-1})
like image 170
Trudbert Avatar answered Mar 17 '26 11:03

Trudbert