Lix*_*ang 4 mongodb node.js mongodb-query aggregation-framework asynchronous-javascript
我是 Nodejs 和 MongoDB 的新手。
这是我的数据集示例:
{
'name': ABC,
'age':24,
'gender':male,
...
}
Run Code Online (Sandbox Code Playgroud)
一般来说,我想做的是先聚合数据,然后再使用它们来查找不同的数据簇。
具体来说,我想知道不同年龄的人有多少。然后,找到每个年龄的人(文件)并存储它们。
这是我的代码:
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);
});
};
});
Run Code Online (Sandbox Code Playgroud)
我期望的 JSON 格式:
{
age:[different documents]
}
Run Code Online (Sandbox Code Playgroud)
例子:
{
20:[{name:A,gender:male,...},{},...],
30:[{name:B,gender:male,...},{},...],
...
}
Run Code Online (Sandbox Code Playgroud)
然而,我得到的是一个空的结果,所以我想可能是由 for 循环引起的。
我不知道如何处理异步回调。
您只需要运行以下管道,用于$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);
});
};
});
Run Code Online (Sandbox Code Playgroud)
使用 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);
});
};
});
Run Code Online (Sandbox Code Playgroud)