我有日记文件。其中包含journal_volumes,期刊问题和期刊文章的详细信息。我必须列出期刊以及每本期刊的数量,期刊和文章的数量。
这是我的文档:
{
"_id" : ObjectId("5c470fc3135edb4413b0ea24"),
"jnl_code" : "KEG",
"jnl_volumes" : [
{
"name" : "1",
"created_date" : "2019-03-01",
"status" : "0",
"issue_flag" : "0",
"jnl_issues" : [
{
"issue_name" : "1",
"created_date" : "2019-03-04",
"jnl_articles" : [
"test",
"test2"
]
},
{
"issue_name" : "2",
"created_date" : "2019-03-04",
"jnl_articles" : [
"a"
]
},
{
"issue_name" : "3",
"created_date" : "2019-03-04",
"jnl_articles" : [
"b"
]
},
{
"issue_name" : "3",
"created_date" : "2019-03-05",
"jnl_articles" : [
"Q"
]
}
]
},
{
"name" : "2",
"created_date" : "2019-03-01",
"status" : "0",
"issue_flag" : "0",
"jnl_issues" : [
{
"issue_name" : "1",
"created_date" : "2019-03-05",
"jnl_articles" : [
"W"
]
},
{
"issue_name" : "1",
"created_date" : "2019-03-05",
"jnl_articles" : [
"S"
]
},
{
"issue_name" : "1",
"created_date" : "2019-03-05",
"jnl_articles" : [
"R"
]
},
{
"issue_name" : "1",
"created_date" : "2019-03-05",
"jnl_articles" : [
"R"
]
}
]
},
{
"name" : "3",
"created_date" : "2019-03-05",
"status" : "0",
"issue_flag" : "0"
}
]
}
我的要求是在单个查询中获取jnl_volumes的数量,jnl_issues的总数和jnl_articles的总数。
感谢Neil Lunn将我重定向到类似的问题(Calculate the count of nested objects with C# )。我参考了答案并写了一个查询:
db.getCollection('rvh_journals').aggregate([
{
$project: {
"volumes" : { "$size" : { "$ifNull" : [ "$jnl_volumes", [] ] } },
"issues" : {
"$sum" : {
"$map" : {
"input" : "$jnl_volumes",
"in": { "$size" : { "$ifNull" : [ "$$this.jnl_issues", [] ] } }
}
}
},
"articles" : {
"$sum" : {
"$map" : {
"input" : "$jnl_volumes.jnl_issues.jnl_articles",
"in" : { "$size" : { "$ifNull" : [ "$$this", [] ] } }
}
}
}
}
}
])
这将返回错误的商品计数。实际文章数为9,但查询返回8
{
"_id" : ObjectId("5c470fc3135edb4413b0ea24"),
"volumes" : 3,
"issues" : 8,
"articles" : 8
}
答案 0 :(得分:0)
是的,在您对上一个问题进行编辑后,我感到很好奇,并注意到您的陈述不正确。
这是正确的:
db.getCollection('rvh_journals').aggregate([
{ "$project": {
"volumes": { "$size": "$jnl_volumes" },
"issues": {
"$sum": {
"$map": {
"input": "$jnl_volumes",
"in": { "$size": { "$ifNull": ["$$this.jnl_issues", [] ] } }
}
}
},
"articles": {
"$sum": {
"$map": {
"input": "$jnl_volumes",
"in": {
"$sum": {
"$map": {
"input": { "$ifNull": [ "$$this.jnl_issues", [] ] },
"in": { "$size": { "$ifNull": [ "$$this.jnl_articles", [] ] } }
}
}
}
}
}
}
}}
])
返回:
{
"_id" : ObjectId("5c470fc3135edb4413b0ea24"),
"volumes" : 3,
"issues" : 8,
"articles" : 9
}
请注意遍历数组。
您可能会去阅读我在that original linked answer上使用过的一些实际单词,因为我会解释说这样的嵌套数组不是一个好主意。 Updating a Nested Array with MongoDB
上有更多关于为什么不是一个好主意的详细信息以及采取其他方法的实用方法答案 1 :(得分:0)
.itcount()-显示不同的计数。 需要显示在$ group中声明的count变量的总数 目前正在根据公司显示。