简体   繁体   中英

How do I access subdocuments in MongoDB queries?

So I have the following code. I need it to run in the MongoDB shell. It queries the database for people with their attribute marked as true. Now I am having trouble because I do not know how to change the numcollect portion of my query into an array. I am trying to average all the numbers in the numcollect collection. I know this code is incorrect but it shows what I'm trying to do. What do I need to change?

Database:

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

Code

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

So first of all this question has nothing to do with MongoDB ( because it uses more or less standard JavaScript implementation ). You simply want to know how to loop over values in a dictionary/object in JavaScript:

for (var i in numcollect) {
    if (numcollect.hasOwnProperty(i)) {
        person.numavg += numcollect[i];
    }
}

This can be one answer:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM