我正在尝试在mongoDB中使用非常基本的聚合查询,然后将其应用于节点。
我正在使用mongoDB中的这个数据集:
> db.grades.find().pretty()
{
"_id" : ObjectId("5276c13ddc170c04635c1eaf"),
"student" : "Joe",
"assignment" : "hw2",
"grade" : 80
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb0"),
"student" : "Joe",
"assignment" : "hw3",
"grade" : 85
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb1"),
"student" : "Joe",
"assignment" : "exam",
"grade" : 100
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb3"),
"student" : "Steve",
"assignment" : "hw2",
"grade" : 90
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb4"),
"student" : "Steve",
"assignment" : "hw3",
"grade" : 100
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb5"),
"student" : "Steve",
"assignment" : "exam",
"grade" : 100
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb7"),
"student" : "Amanda",
"assignment" : "hw2",
"grade" : 90
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb8"),
"student" : "Amanda",
"assignment" : "hw3",
"grade" : 80
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb9"),
"student" : "Amanda",
"assignment" : "exam",
"grade" : 100
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eba"),
"student" : "Susan",
"assignment" : "hw1",
"grade" : 100
}
{
"_id" : ObjectId("5276c13ddc170c04635c1ebb"),
"student" : "Susan",
"assignment" : "hw2",
"grade" : 90
}
{
"_id" : ObjectId("5276c13ddc170c04635c1ebc"),
"student" : "Susan",
"assignment" : "hw3",
"grade" : 85
}
{
"_id" : ObjectId("5276c13ddc170c04635c1ebd"),
"student" : "Susan",
"assignment" : "exam",
"grade" : 80
}
{
"_id" : ObjectId("5276c13cdc170c04635c1eae"),
"student" : "Joe",
"assignment" : "hw1",
"grade" : 90,
"date_returned" : ISODate("2013-11-03T23:44:18.774Z")
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb2"),
"student" : "Steve",
"assignment" : "hw1",
"grade" : 80,
"date_returned" : ISODate("2013-11-03T23:44:31.496Z")
}
{
"_id" : ObjectId("5276c13ddc170c04635c1eb6"),
"student" : "Amanda",
"assignment" : "hw1",
"grade" : 100,
"date_returned" : ISODate("2013-11-04T00:59:49.446Z")
}
>
> db.grades.find().pretty().count()
16
>
现在,这是我想在节点中运行的聚合查询:
> db.grades.aggregate([{$group: {_id: "$student"}}])
{
"result" : [
{
"_id" : "Susan"
},
{
"_id" : "Amanda"
},
{
"_id" : "Steve"
},
{
"_id" : "Joe"
}
],
"ok" : 1
}
这是我在我正在使用的节点中的尝试。我正在使用快递来设置路线。
app.get('/Work5_6', function(req, res){
// connect to collection
db.collection('grades').aggregate( {$group: {_id: "$student"}} , function (err, result) {
//if there's an error
if(err) throw err;
//if there is no more results
if (!result) {
console.dir("xNo Document found!");
res.send('This is a test page...',200);
}
//...do stuff here to your doc
console.dir("value of result is:");
console.dir(result);
});
});
这是我进入控制台的结果:
'value of result is:'
[]
如何访问从节点中的聚合查询返回的“result”值?感谢一些帮助。