Manish Trivedi
Manish Trivedi

Reputation: 3559

sorting is not working in mongodb

I am struggling with sorting query!! When I will execute same query with mongo shell

db.locations.find({"$and":[{"timestamp":{"$gte":1438328404766,"$lte":1438329404766}}]}).sort({"timestamp":1})

getting sorted result. But doing it by code then getting unordered result. Can you look following code and let me know if anything is going wrong with this code.

//part of function(condition, offset, limit, sortByColumn, ordering, fields)

        logger.debug('Filter condition is '+JSON.stringify(condition));

        var instance ;

        if (fields) {
            instance = self.model.find(condition, fields);
        } else {
            instance = self.model.find(condition);
        }

        // start record from
        if (!_.isEmpty(offset)) {
            logger.debug('Offset is : '+ offset);
            instance.skip(offset);
        }

        if (sortByColumn ) {
            //default ordering is asc
            ordering = !(ordering) ? 1 : ordering;          
            instance.sort({sortByColumn: ordering});

            logger.debug('sorting with sortByColumn : '+sortByColumn+' Ordering : '+ ordering);
        }

        if (!_.isEmpty(limit)) {
            logger.debug('Limit is : '+ limit);

            instance.limit(limit);
        }

        instance.execAsync()
                .then(function(results) {

                    logger.debug('result is : ' + JSON.stringify(results));

                    return resolve(results);
                }).catch(function(error) {
                    return reject(error);
                });

Upvotes: 0

Views: 61

Answers (1)

Blakes Seven
Blakes Seven

Reputation: 50406

In JavaScript you assign a variable to the key of an object like this:

    if (sortByColumn ) {
        //default ordering is asc
        ordering = !(ordering) ? 1 : ordering; 

        // declare an object
        var sorting = {};

        // Assign like this
        sorting[sortByColumn] = ordering;

        instance.sort(sorting);     // Use the object

        logger.debug('sorting with sortByColumn : '+sortByColumn+' Ordering : '+ ordering);
    }

So you use the "bracket" notation to assign a variable, otherwise it is just treated as a "literal" key name, thus:

var sortByColumn = "theColumnIAskedFor";
{ "sortByColumn": 1 }          // Not what I want :(

Mine comes out as:

var sortByColumn = "theColumnIAskedFor";
{ "theColumnIAskedFor": 1 }    // Yey! :->

Upvotes: 1

Related Questions