In my script, I have an array outside mongodb called title. The dataset in mongodb contains fields that I do not want to include (Dataset_1). I am using an indexOf function to match values and create a ranking.
The structure of Dataset_1 is as follows:
geotype state numbers
state Alabama 14
state Alaska 344
state California 144
state New York 255
state Washington 233
state Guam 255
state Puerto Rico 36
state Virgin Islands 366
state Delaware 434
state New Mexico 444
state Maryland 544
...
The var title array looks like this:
var title = [
'Alabama',
'Alaska',
'California',
'New York',
'Washington',
'Delaware',
'New Mexico',
'Maryland'
...]
It's important to note that var title only contains US states, not territories.
My objective is to rank the states by 'numbers' in a new column 'ranking' if there is a match with the title array. Territories like Guam and Puerto Rico should not be ranked.
if (Dataset_1[column].indexOf(title) > -1) {
execute
}
Below is the code I am using to create rankings using javascript with mongodb dataset update:
//This script includes var title as well
var rank = 0;
var rank_value = Infinity;
db.Dataset_1.find({'geo_type': 'state'}).sort({'numbers': -1}).forEach(function(doc){
if (doc['state'].indexOf(title) > -1) {
if (doc['numbers'] < rank_value) {
rank_value = doc['numbers'];
rank = rank + 1;
}
if (doc['numbers'] != null) {
db.Dataset_1.update({
'_id' : doc['_id']
},{$set: {
'ranking' : rank
}})
}
}
});
However, this code ranks all the fields instead of only the matches. Am I using the indexOf function correctly?
I have experimented with different ways to solve this issue, but I either encounter syntax errors or include unwanted fields.
To summarize, here is an example output:
geotype state numbers ranking
state Alabama 14 11
state Alaska 344 5
...