本文介绍了在MongoDB中检索数组中项目的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于

-聚合:向$ unwind添加选项以发出数组索引

-在mongodb查询中获取项目的索引

我有这个用例.

最美味的水果排名:

{"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"]}

我试图获取1月1日至12月31日每一天的梨"排名,现在我需要获取所有数组并执行indexOf在我的应用程序中.如果在MongoDB中有某种方法可以加快我的应用程序的速度,并且只返回"Pear"的索引而不是整个Array.

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 indexOfin 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.

我查看了地图精简,但是文档似乎建议您需要一个不起作用的reduce函数.

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

还查看了聚合框架,但是该 JIRA 票证似乎表明该票证尚未实施.

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.

任何帮助将不胜感激!

推荐答案

尚未测试此代码,但应该可以.

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

假定存储该数据库的数据库名称为tastyFruits ...

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

这篇关于在MongoDB中检索数组中项目的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 17:46