3

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 Answer 1

2

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"));
});
Sign up to request clarification or add additional context in comments.

4 Comments

Interesting concept. Unfortunately that only logs the indexes in the MongoDB logs but doesn't actually return the indexes. ps. its print() and not console.log()
If you want to return the indexes, simply push those pear ratings to an array and return the array. Not sure what language you're using, so I can't help you there.
Thanks! It works. Its a little bit sketchy because of injection problems but it works and its super fast.
hi mjkaufer, would you mind changing your answer to print instead of console.log for future clarity?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.