7

I have a database with the following document structure:

{
    "_id" : ObjectId("520bea012ab230549e749cff"),
    "Day" : 1,
    "Time" : 54,
    "State" : "Vermont",
    "Airport" : "BTV",
    "Temperature" : 39,
    "Humidity" : 57,
    "Wind Speed" : 6,
    "Wind Direction" : 170,
    "Station Pressure" : 29.6,
    "Sea Level Pressure" : 150
}

I need to find the most high 'Temperature' for each 'State' (i.e. e.g. there are 100 document with 'State':'Vermont') and add entry 'month_high':true into this document (that has the most high temperature)

Here is my code: http://pastebin.com/UbACLbSF

But when I run the program in shell I get the following error:

MongoError: Can't canonicalize query: BadValue bad order array [2]

Zanon
  • 29,231
  • 20
  • 113
  • 126
Dennis
  • 487
  • 5
  • 15

2 Answers2

3

You should be passing in an object, not an array

cursor.sort({"State": 1, "Temperature": -1});
Yuri Zarubin
  • 11,439
  • 4
  • 30
  • 33
  • this variant raises error - TypeError: Cannot read property 'State' of null – Dennis Aug 15 '15 at 10:13
  • Well that's a different error in a different part of the application. Looks like you probably have a document that doesn't have a 'State' property, so when you're trying to perform a comparison you get an error. – Yuri Zarubin Aug 15 '15 at 17:31
  • no... 'State' property is in every document... I checked it... I pasted in code - console.dir(doc) in cycle and got all documents with this property... it seems I begin understanding of problem... callback cursor.each returns 'null' ... but I do not understand how it impacts loop performance... – Dennis Aug 17 '15 at 15:11
  • This answer is wrong regarding the Node.js driver. You need to use an array and *not* an json object to keep the sort order. The [documentation](https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html?highlight=sort) is not so clear about this, but [this](https://www.youtube.com/watch?t=219&v=GD78tbm_qvQ) official tutorial video is. – Zanon Aug 18 '15 at 03:31
0

You just need the 'State' and 'Temperature', right? So try to project it before sorting. I've tested the following code and it worked:

var query = {};
var projection = { 'State':1, 'Temperature':1 };
var options = { 'sort' : [['State',1], ['Temperature',-1]] };

var cursor = db.collection('data').find(query, projection, options);
Zanon
  • 29,231
  • 20
  • 113
  • 126