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!

Community
  • 1
  • 1
makeshifthoop
  • 127
  • 1
  • 8

1 Answers1

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"));
});
mjkaufer
  • 3,311
  • 3
  • 19
  • 52
  • 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() – makeshifthoop Jan 12 '14 at 02:11
  • 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. – mjkaufer Jan 12 '14 at 04:14
  • Thanks! It works. Its a little bit sketchy because of injection problems but it works and its super fast. – makeshifthoop Jan 13 '14 at 18:32
  • hi mjkaufer, would you mind changing your answer to print instead of console.log for future clarity? – makeshifthoop Jan 13 '14 at 18:33