Question

I have following kind of objects stored into mongodb:

 { _id: 5319b78ba96ea4ef5c99dd55,
    name: 'Test',
channel: 'Right one', showed: { _isAMomentObject: true, _i: '12.3.2014 21:45', _f: 'DD.MM.YYYY HH:mm', _l: null, _strict: null, _isUTC: false, _pf: [Object], _a: [Object], _d: Wed Mar 12 2014 21:45:00 GMT-0400 (EDT), _isValid: true, _lang: [Object] } },

I want to fetch last 30 objects in date order. I have tried sorting in this way (and also with showed._d) put it seems to sort things in alphabetic order not by date.

db.open(function(err, db) {
                        var options = {
                            'limit': 30,
                            'sort': ['showed._i','desc']
                        }

                        db.collection('programs', function(err, collection) {
                                collection.find({}, options, function(err, docs) {
                                        docs.toArray(function(err, docs) {
                                                res.json(docs);
                                        });
                                });
                        });
                });
Était-ce utile?

La solution

For sorting in descending order, you'll need to use '-1' instead of 'desc'. This is how it's done in the shell:

db.collection.find({}).sort({'showed._i':-1}).limit(30)

Also, the field "showed._i" is stored as a string, rather than a Date. The values will need to converted to Date type for the correct results to be returned by Sorting.

Check this post for an approach to convert string to Date type

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top