mongoDb中嵌套文档结构的查询
我试图查询下面的文档结构mongoDb中嵌套文档结构的查询,mongodb,nosql,aggregation-framework,aggregate-functions,Mongodb,Nosql,Aggregation Framework,Aggregate Functions,我试图查询下面的文档结构 { _id: '7ja9sjkadja', parent: { parentName: 'Super', firstGenerations: [ { name: 'First Generation', secondGenerations: [ { name: 'Second Generation 1',
{
_id: '7ja9sjkadja',
parent: {
parentName: 'Super',
firstGenerations: [
{
name: 'First Generation',
secondGenerations: [
{
name: 'Second Generation 1',
value: 'Married'
},
{
name: 'Second Generation 2',
value: 'Single'
},
{
name: 'Second Generation 3',
value: 'Single'
}
]
}
]
}
}
预期产出:
{
firstGenerationName: 'First Generation',
totalCount: 3
values: [
{
categoryName: 'Married (1)',
count: 1,
firstGenerationName: 'First Generation'
},
{
categoryName: 'Single (2)',
count: 2,
firstGenerationName: 'First Generation'
}
]
}
我尝试的查询:
db.generations.aggregate([
通过从父数组中获取一个值并从第二个数组中计数,我可以正确地放松,但无法使用club group功能
任何帮助都将不胜感激基本上,您需要运行两次
$group
以首先获取内部计数:
db.collection.aggregate([
{
$unwind: "$parent"
},
{
$unwind: "$parent.firstGenerations"
},
{
$unwind: "$parent.firstGenerations.secondGenerations"
},
{
$group: {
_id: {
fgName: "$parent.firstGenerations.name",
sgValue: "$parent.firstGenerations.secondGenerations.value"
},
count: { $sum: 1 }
}
},
{
$group: {
_id: "$_id.fgName",
values: {
$push: {
categoryName: { $concat: [ "$_id.sgValue", " (", { $toString: "$count" }, ")" ] },
count: "$count",
firstGenerationName: "$_id.fgName"
}
}
}
},
{
$project: {
_id: 0,
firstGenerationName: "$_id",
values: 1,
totalCount: { $sum: "$values.count" }
}
}
])
db.collection.aggregate([
{
$unwind: "$parent"
},
{
$unwind: "$parent.firstGenerations"
},
{
$unwind: "$parent.firstGenerations.secondGenerations"
},
{
$group: {
_id: {
fgName: "$parent.firstGenerations.name",
sgValue: "$parent.firstGenerations.secondGenerations.value"
},
count: { $sum: 1 }
}
},
{
$group: {
_id: "$_id.fgName",
values: {
$push: {
categoryName: { $concat: [ "$_id.sgValue", " (", { $toString: "$count" }, ")" ] },
count: "$count",
firstGenerationName: "$_id.fgName"
}
}
}
},
{
$project: {
_id: 0,
firstGenerationName: "$_id",
values: 1,
totalCount: { $sum: "$values.count" }
}
}
])