32

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!

David G
  • 94,763
  • 41
  • 167
  • 253
dzm
  • 22,844
  • 47
  • 146
  • 226

1 Answers1

61

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

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 1
    i think this will only use the first date in the array for sorting. so if you wanted to sort descending, and your later dates were appended to the end rather than inserted to the beginning, your sort would be incorrect. – Rob Allsopp Dec 06 '17 at 20:30
  • @RobAllsopp how do you fix that? I sorted descending and the documents that dont have the nested value are displayed on top – Naveed Mar 05 '21 at 08:37