MongoDB MapReduce:在映射函数中使用位置运算符 $
我有一个包含如下条目的集合:
{"userid": 1, "contents": [ { "tag": "whatever", "value": 100 }, {"tag": "whatever2", "value ": 110 } ] }
我正在使用诸如 {"contents.tag": "whatever"} 之类的查询对此集合执行 MapReduce。
我想要在地图函数中执行的操作是发出与数组“内容”中与查询匹配的条目相对应的字段“值”,而无需迭代整个数组。在正常情况下,我可以使用 $ 位置运算符与内容.$.value 之类的内容来做到这一点。但在 MapReduce 的情况下,它不起作用。
总而言之,这是我现在拥有的代码:`
map=function(){
emit(this.userid, WHAT DO I WRITE HERE TO EMIT THE VALUE I WANT ?);
}
reduce=function(key,values){
return values[0]; //this reduce function does not make sense, just for the example
}
res=db.runCommand(
{
"mapreduce": "collection",
"query": {'contents.tag':'whatever'},
"map": map,
"reduce": reduce,
"out": "test_mr"
}
);`
有什么想法吗?
谢谢 !
I have a collection with entries that look like that :
{"userid": 1, "contents": [ { "tag": "whatever", "value": 100 }, {"tag": "whatever2", "value": 110 } ] }
I'm performing a MapReduce on this collection with queries such as {"contents.tag": "whatever"}.
What I'd like to do in my map function is emiting the field "value" corresponding to the entry in the array "contents" that matched the query without having to iterate through the whole array. Under normal circumstances, I could do that using the $ positional operator with something like contents.$.value. But in the MapReduce case, it's not working.
To summarize, here is the code I have right now :`
map=function(){
emit(this.userid, WHAT DO I WRITE HERE TO EMIT THE VALUE I WANT ?);
}
reduce=function(key,values){
return values[0]; //this reduce function does not make sense, just for the example
}
res=db.runCommand(
{
"mapreduce": "collection",
"query": {'contents.tag':'whatever'},
"map": map,
"reduce": reduce,
"out": "test_mr"
}
);`
Any idea ?
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果不迭代整个数组,这将不起作用。在 MongoDB 中,查询旨在匹配整个文档。
在处理 Map/Reduce 时,查询只是简单地修剪传入
map
函数的文档数量。但是,map
函数不知道所运行的查询。两人断绝关系。M/R 周围的源代码位于此处< /a>.
即将推出的聚合功能将更符合这一愿望。但这个功能没有时间表。
This will not work without iterating over the whole array. In MongoDB a query is intended to match an entire document.
When dealing with Map / Reduce, the query is simply trimming the number of documents that are passed into the
map
function. However, themap
function has no knowledge of the query that was run. The two are disconnected.The source code around the M/R is here.
There is an upcoming aggregation feature that will more closely match this desire. But there's no timeline on this feature.
决不。我也遇到过同样的问题。迭代是必要的。
你可以这样做:
No way. I've had the same problem. The iterate is necessary.
You could do this: