2

所以我有以下代码。我需要它在 MongoDB shell 中运行。它在数据库中查询属性标记为 true 的人。现在我遇到了麻烦,因为我不知道如何将查询的 numcollect 部分更改为数组。我正在尝试平均 numcollect 集合中的所有数字。我知道这段代码不正确,但它显示了我正在尝试做的事情。我需要改变什么?

数据库:

{
     "name":"John Doe",
     "attribute":"true",
     "numcollect":{
        "one":12,
        "two":22,
        "three":44,
        "four":79
     }
},
{
     "name":"Jane Doe",
     "attribute":"true",
     "numcollect":{
        "one":13,
        "two":55,
        "three":18
     }
}

代码

var people= [];
var index = 0;
db.test.find({"attribute":"true"}).forEach(
    function(myDoc) { 
        var person=new Object();
        person.name=myDoc.name;
        person.numcollect=myDoc.numcollect;
        person.numavg = 0;
        var i = 0;
        for(i = 0; i<numcollect.length; i++)
        {
            person.numavg+=person.numcollect[i];
        }
        person.numavg/=i;
        people[index]=person;
        index++;
    } 
);
4

2 回答 2

1

所以首先这个问题与 MongoDB 无关(因为它或多或少地使用了标准的 JavaScript 实现)。您只是想知道如何在 JavaScript 中循环遍历字典/对象中的值:

for (var i in numcollect) {
    if (numcollect.hasOwnProperty(i)) {
        person.numavg += numcollect[i];
    }
}
于 2013-02-08T07:28:32.360 回答
0

这可以是一个答案:

collection.mapReduce(function(){
            for(var key in this.numcollect)
                emit(this._id, this.numcollect[key])
        }, function(key, values){
            return Array.sum(values)
        },{
            out:{inline:1}
        }, function(err, doc){
            if(err){
                console.log("mapReduce ERROR", err);
            }else{
                console.log("mapReduce Result", doc);
            }
        })
于 2013-08-14T01:38:57.633 回答