【问题标题】:Retrieve index of item in array in MongoDB检索MongoDB中数组中的项目索引
【发布时间】:2014-01-30 21:08:54
【问题描述】:

类似

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

-Get index of an item within mongodb query

我有这个用例。

最美味水果排行榜:

{"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 日每一天的“Pear”排名,现在我需要重新获取所有数组并执行 indexOf 在我的应用程序中。如果在 MongoDB 中有某种方法可以加快我的应用程序的速度,并且只返回“Pear”的索引而不是整个数组。

我查看了Map Reduce,但documentation 似乎建议您需要一个不起作用的reduce 函数。

还查看了Aggregation framework,但这张JIRA 票似乎表明它尚未实施。

最后,我查看了Server Side Scripting,但对于一个简单的用例来说,它似乎太高级了。

任何帮助将不胜感激!

【问题讨论】:

    标签: mongodb mongoid mongodb-query mongoid3


    【解决方案1】:

    尚未测试此代码,但它应该可以工作。

    假设存储它的数据库名称是tastyFruits...

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

    【讨论】:

    • 有趣的概念。不幸的是,这只记录了 MongoDB 日志中的索引,但实际上并没有返回索引。附言。它的 print() 而不是 console.log()
    • 如果您想返回索引,只需将这些梨评级推送到一个数组并返回该数组。不确定您使用的是什么语言,所以我无法为您提供帮助。
    • 谢谢!有用。由于注入问题,它有点粗略,但它可以工作并且超级快。
    • 嗨,mjkaufer,您是否介意将您的答案更改为 print 而不是 console.log 以便将来清楚?
    猜你喜欢
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2013-08-10
    • 2014-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多