【发布时间】:2018-10-02 00:51:36
【问题描述】:
我是 MongoDB 的新手,我想使用聚合函数来检查 type == topic 并获得以下输出
预期输出
[
{
conceptName : 59d98cfd1c5edc24e4024d00
totalCount : 2
},
{
conceptName : 59d98cfd1c5edc24e4024d03
totalCount : 1
}
]
样本输入db.GroupContents
{
"_id" : "5a0948bb1c5edc7a5000521a",
"type" : "topic",
"groupID" : "5a0948bb1c5edc7a5000521a",
"pedagogyID" : "59d98cfa1c5edc24e40249a3",
}
样本输入db.PedagogyNodes
{
"_id" : "59d98cfa1c5edc24e40249a3",
"latestVersion" : "59d98cfa1c5edc24e402497f_1",
"createdAt" : "2017-10-08 04:27:06",
"updatedAt" : "2017-10-08 04:27:06"
}
样本输入db.PedagogyVersions
{
"_id" : "59d98cfa1c5edc24e402497f_1",
"type" : "topic",
"contentNodes" : {
"LearningNodes" : [
"59d98cfd1c5edc24e4024d00",
"59d98cfd1c5edc24e4024d03",
"59d98cfd1c5edc24e4024d00",
]
},
"createdAt" : "2017-10-08 04:27:06",
"updatedAt" : "2017-10-08 04:27:06"
}
到目前为止我已经尝试过什么
var groupID = "5a0948bb1c5edc7a5000521a"; // Step 1
var records;
var pnDoc;
var pvDoc;
db.GroupContents.find({groupID : groupID}).forEach(function (doc){ // Step 2
var pedagogyID = doc.pedagogyID;
var records = db.getSiblingDB('PedagogyService');
records.PedagogyNodes.find({_id : pedagogyID}).forEach(function (pnDoc) { // Step 3
var latestVersion = pnDoc.latestVersion;
// addded aggregate function here
records.PedagogyVersions.aggregate([
{
$match:{_id:latestVersion} // Step 4
},
{
$unwind:"$contentNodes.LearningNodes"
},
{
$group:
{
_id:"$contentNodes.LearningNodes",
count:{$sum:1}
}
}
])
})
});
我无法根据我的预期答案编写数据库查询,请帮助。
了解我的要求
Step : 1 => I am passing `groupID = 5a0948bb1c5edc7a5000521a`
Step : 2 => we have to check from GroupContents where groupID = groupID then we have to take `pedagogyID`
Step : 3 => we have to check from PedagogyNodes where _id = pedagogyID then we have to take `latestVersion`
Step : 4 => we have to check from PedagogyVersions where _id = latestVersion then we have to take `contentNodes->LearningNodes`
Step : 5 => Finally we have to do the aggregation then we have display the result
【问题讨论】:
-
如果您可以编辑您的问题以包含来自每个相关集合的示例文档作为输入,这将非常有帮助,因为它有助于组成正确的聚合管道,您已经给了我们预期的输出所以没关系。
-
@chridam,我已经编辑了我的问题,我也给了我的示例文档
-
现在我必须检查只有
db.PedagogyVersions集合,如果您更新聚合查询方式,那对我来说很好 -
只需
$unwind数组并使用$group。像这样db.collection.aggregate([ { $unwind: "$contentNodes.contentNodes" }, { $group: { _id: "$contentNodes.contentNodes", totalCount: { $sum: 1 } } } ]) -
@Anthony Winzlet,我试过你的代码,但没有打印出来
标签: mongodb mongodb-query aggregation-framework