Retrieve index of item in array in MongoDB

…衆ロ難τιáo~ 提交于 2019-12-23 19:04:37

问题


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:


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"));
});


来源:https://stackoverflow.com/questions/21068966/retrieve-index-of-item-in-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!