node.js - MongoError: Can't canonicalize query: BadValue bad order array [2]
Asked Answered
E

2

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]

Edelmiraedelson answered 14/8, 2015 at 17:34 Comment(0)
W
3

You should be passing in an object, not an array

cursor.sort({"State": 1, "Temperature": -1});
Walcott answered 15/8, 2015 at 4:58 Comment(4)
this variant raises error - TypeError: Cannot read property 'State' of nullEdelmiraedelson
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.Walcott
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...Edelmiraedelson
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 is not so clear about this, but this official tutorial video is.Carrasquillo
C
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);
Carrasquillo answered 18/8, 2015 at 3:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.