mongodb映射从子文档发出键

mongodb映射从子文档发出键,mongodb,mapreduce,Mongodb,Mapreduce,我有一份文件,其中包括一个子文件: { "_id" : ObjectId("XXXXX"), "SearchKey" : "1234", "SearchTerms" : { "STA" : ["1"], "STB" : ["asdfasdf"], "STC" : ["another"] } } SearchTerm元素不是固定的——例如,有时我们会有没有STC的STA 我可以这样做: var map = funct

我有一份文件,其中包括一个子文件:

{
    "_id" : ObjectId("XXXXX"),
    "SearchKey" : "1234",
    "SearchTerms" : {
        "STA" : ["1"],
        "STB" : ["asdfasdf"],
        "STC" : ["another"]
    }
}
SearchTerm元素不是固定的——例如,有时我们会有没有STC的STA

我可以这样做:

var map = function() {
    for (key in this.SearchTerms)
    {
        emit(key, 1);
    }
}
但我不能这么做:

var map = function() {
    for (var i=0; i< this.SearchTerms.length; i++)
    {
        emit(this.SearchTerms[i], 1)
    }
}
var map=function(){
for(var i=0;i
因为后者在reduce之后不会产生任何结果。为什么不呢

顺便说一句,我需要做的是计算所有文档中搜索词的叉积,也就是说,在上面的例子中找到(STA和STB)和(STA和STC)以及(STB和STC)的发生率。如果有人知道如何立即这样做,效果会更好


一如既往,感谢您的帮助

这是因为
This.SearchTerms
是一个字典/子文档,而不是数组<代码>此.SearchTerms[0]
不存在

关于第二个问题:类似的方法应该有效:

for (key1 in this.SearchTerms)
{
  for (key2 in this.SearchTerms)
  {       
    if (key1 < key2)
    {
      key = [key1, key2];
      emit(key, 1);
    }
  }
}
for(此.SearchTerms中的键1)
{
for(本.SearchTerms中的键2)
{       
如果(键1<键2)
{
键=[key1,key2];
发射(键,1);
}
}
}

您发出的键应该是两个键的组合

    var map = function() {
        if(!this.SearchTerms) return;
        for(var i = 0 ; i < this.SearchTerms.length; i++){
            var outerKey = this.SearchTerms[i];
            for(var j = i + 1; j < this.SearchTerms.length; j++){
               var innerKey = this.SearchTerms[j];
               // assuming you don't care about counting (STA and STC) separately from (STC and STA), 
               // then order doesn't matter, lets make sure both occurences have the same key.
               var compositeKey = (outerKey < innerKey) ? outerKey+"_"+innerKey : innerKey+"_"+outerKey; 
               emit(compositeKey, 1);
            }
        }
    }
var map=function(){
如果(!this.SearchTerms)返回;
for(var i=0;i
我收到一个错误:“id不能是数组”,但如果我执行key=key1+“”+key2之类的操作,它就会工作。万分感谢!总的想法很好,但是上面的方法不算所有的组合两次吗?一次用于outerkeyouterkey?每对存储两次,这完全没有必要,只是浪费了磁盘和CPU。这是怎么回事?请注意,内部循环从
i+1
开始?你能提供一个更好的答案吗?