简体   繁体   中英

How to access data returned by group reduce in Mongo?

I have a JavaScript file as

var x = new Mongo('127.0.0.1:27017');
var db = x.getDB('user');
var r = db.runCommand({"group" : {
                                "ns" : "track_user", "key" : {userId : 1}, "initial" : {
                         count:0 }, cond: {
                                        uri: {
                                            $regex: 'sm'
                                        } }, "$reduce" : function(doc, prev) {
                                            } } }       }});


while(r.hasNext()){
    rs = r.next();  
}       

I am not able to run through results returned by group reduce. output of group reduce run via shell is something like

{
    "retval" : [
        {
            "userId" : 0,
            "created" : "2013-08-08 11:32:15",
            "uri" : "abc.com",
            "uri_set" : [
                "xyz.com"
            ]
        },...

    ],
    "count" : 14,
    "keys" : 6,
    "ok" : 1
}

hasNext is giving error as

Sat Nov 23 00:53:40.351 JavaScript execution failed: TypeError: Object [object Object] has no method 'hasNext' at /var/www/admin/app/controllers/newjavascript1.js:L62

The problem is that db.runCommand() does not return a cursor, so none of the cursor methods are going to work on it. You're returning a document with the results nested inside, so you're going to have to work with the data a different way.

You should be able to either use map or each , depending on what you're trying to do:

var mySet = r.retval;

mySet.forEach( function(doc) {
    console.log( doc );
});

Or, whatever you need it to do.

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