Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB sorting by nested object value

Tags:

I'm trying to sort results based on the values of a nested object. Using node-mongodb-native, I'm doing this:

    this.collection.find({
          "_id": ObjectID(item_id) }, 
        { "items": 1 },
        { sort : { items.date : 1 }
    }, function(err, result) {
        if (err) {
            callback(err);
        } else {
            callback(null, result);
        }
    });

I get an unexpected token error for items.date.

items is an array of objects. Some documents it's an empty array, others it contains data, which contains a date field.

Thank you!

like image 464
dzm Avatar asked Aug 20 '12 01:08

dzm


1 Answers

When using dot notation you need to put the key value in quotes, so your sort object should look like this instead:

sort: {
    "items.date" : 1
}

That will sort ascending by minimum date value in each doc's items array

like image 76
JohnnyHK Avatar answered Oct 13 '22 23:10

JohnnyHK