【问题标题】:Nodejs + Mongodb: find data after aggregationNodejs + Mongodb:聚合后查找数据
【发布时间】:2017-07-19 07:48:51
【问题描述】:

我是 Nodejs 和 MongoDB 的新手。
这是我的数据集的示例:

{ 
  'name': ABC,
  'age':24,
  'gender':male,
  ...
}

一般来说,我想做的是在使用它们之前聚合数据以找到不同的数据集群。
具体来说,我想知道有多少人处于不同的年龄。然后,找到每个年龄的人(文档)并存储它们。

这是我的代码:

MongoClient.connect(url, function(err, db) {
    if(err) { 
        console.log('Unable to connect to the mongoDB server. Error:', err); 
    } else { 
        db.collection('test').aggregate(
        [
          { $group: { _id: "$age" , total: { $sum: 1 } } },
          { $sort: { total: -1 } } 
        ]).toArray(function(err, result) {
            assert.equal(err, null);
            age = [];
            for(var i in result) {
                age.push(result[i]['_id'])
            };
            ageNodes = {};
            for(var i in age) {
                 nodes = [];
                 var cursor = db.collection('test').find({'age':age[i]});
                 // query based on aggregated data
                 cursor.each(function(err,doc){
                    if(doc!=null){
                        nodes.push(doc);
                    } else {
                        console.log(age[i]);
                        ageNodes[age[i]] = nodes;
                    }
                })
            }
            res.json(ageNodes);
        });
    };
});

我预期的 JSON 格式:

{
  age:[different documents]
}

示例:

{
  20:[{name:A,gender:male,...},{},...],
  30:[{name:B,gender:male,...},{},...],
  ...
}

但是,我得到的是一个空结果,所以我认为这可能是由 for 循环引起的。
我不知道如何处理异步回调。

【问题讨论】:

    标签: node.js mongodb mongodb-query aggregation-framework asynchronous-javascript


    【解决方案1】:

    您只需运行以下管道,它使用 $push 将根文档(由管道中的 $$ROOT 系统变量表示)添加到数组每个年龄段:

    使用 MongoDB 3.4.4 及更高版本:

    MongoClient.connect(url, function(err, db) {
        if(err) { 
            console.log('Unable to connect to the mongoDB server. Error:', err); 
        } else { 
            db.collection('test').aggregate([
                { '$group': { 
                    '_id': '$age', 
                    'total': { '$sum': 1 }, 
                    'docs': { '$push': '$$ROOT' }
                } },
                { '$sort': { 'total': -1 } },
                { '$group': {
                    '_id': null,
                    'data': {
                        '$push': {
                            'k': '$_id',
                            'v': '$docs'
                        }
                    }
                } },
                { '$replaceRoot': {
                    'newRoot': { '$arrayToObject': '$data' }
                } }    
            ]).toArray(function(err, results) {
                console.log(results);
                res.json(results);
            });
        };
    });
    

    使用 MongoDB 3.2 及以下版本:

    MongoClient.connect(url, function(err, db) {
        if(err) { 
            console.log('Unable to connect to the mongoDB server. Error:', err); 
        } else { 
            db.collection('test').aggregate([
                { '$group': { 
                    '_id': '$age', 
                    'total': { '$sum': 1 }, 
                    'docs': { '$push': '$$ROOT' }
                } },
                { '$sort': { 'total': -1 } } 
            ]).toArray(function(err, results) {
                console.log(results);
                var ageNodes = results.reduce(function(obj, doc) { 
                    obj[doc._id] = doc.docs
                    return obj;
                }, {});
                console.log(ageNodes);
                res.json(ageNodes);
            });
        };
    });
    

    【讨论】:

    • 谢谢。但是这一行出现了错误——'docs': { '$push': '$$ROOT' }。 SyntaxError: 意外的字符串
    • 打错了,忘记在'total': { '$sum': 1 }后面加逗号
    猜你喜欢
    • 1970-01-01
    • 2022-01-03
    • 2017-09-22
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多