gpt4 book ai didi

node.js - Nodejs + Mongodb : find data after aggregation

转载 作者:行者123 更新时间:2023-12-02 01:38:36 24 4
gpt4 key购买 nike

我是 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 循环引起的。
我不知道如何处理异步回调。

最佳答案

您只需要运行以下管道,该管道使用 $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);
});
};
});

关于node.js - Nodejs + Mongodb : find data after aggregation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42507083/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com