Retrieve index of item in array in MongoDB

1.4k Views Asked by At

similar to

-Aggregation: add option to $unwind to emit array index

-Get index of an item within mongodb query

I have this use case.

Tastiest Fruit Rankings:

{"date": "Jan 1st",
"fruit_ranking": ["Apple", "Orange", "Grape", "Kiwi", "Mango", "Pear"]},
{"date": "Jan 2nd",
"fruit_ranking": ["Orange", "Grape", "Kiwi", "Pear", "Apple"]}
.....
{"date": "Dec 31st",
"fruit_ranking":  ["Kiwi", "Apple", "Grape", "Mango", "Pear"]}

I'm trying to grab the ranking of "Pear" for each day Jan 1st - Dec 31st and right now I need to grab all of the arrays back and do indexOf in my application. Would speed up my application quite a bit if theres some way of doing this in MongoDB and just return the index of "Pear" instead of the whole Array.

I looked into Map Reduce but the documentation seem to suggest you need to have a reduce function which doesn't work.

Also looked in to Aggregation framework but this JIRA ticket seems to suggest its not implemented yet.

Lastly, I looked into Server Side Scripting but it seems too advanced for a simple use case.

Any help would be greatly appreciated!

1

There are 1 best solutions below

4
On BEST ANSWER

Haven't tested this code, but it should work.

Presuming the db name where this is stored in is tastyFruits...

tastyFruits.find({}).forEach(function(a){
console.log("Date: " + a.date);
console.log("Pear rating: " + a.fruit_ranking.indexOf("Pear"));
});