提供下列文件:
{
"visitas": {
"visita": [{
"id": "4fc7900e-8e9d-432e-bf38-e9c0b5a10cd9",
"data": "2021-09-16",
"morada": {
"pais": "Portugal",
"cidade_origem": "Penafiel"
},
"pessoas": {
"pessoa": [{
"nome": "pessoa1",
"data_nascimento": "2021-12-29"
}, {
"nome": "pessoa2",
"data_nascimento": "2021-12-29"
}, {
"nome": "pessoa3",
"data_nascimento": "2021-12-29"
}]
}
}, {
"id": "943c0e88-3eda-48ef-8105-6c48cde093a7",
"data": "2021-09-18",
"morada": {
"pais": "Portugal",
"cidade_origem": "Penafiel"
},
"pessoas": {
"pessoa": [{
"nome": "pessoa1",
"data_nascimento": "2021-12-29"
}, {
"nome": "pessoa2",
"data_nascimento": "2021-12-29"
}, {
"nome": "pessoa3",
"data_nascimento": "2021-12-29"
}]
}
}, {
"id": "877e1108-251e-410c-95e3-8df5dbfbe4e2",
"data": "2021-09-18",
"morada": {
"pais": "Portugal",
"cidade_origem": "Penafiel"
},
"pessoas": {
"pessoa": [{
"nome": "pessoa1",
"data_nascimento": "2021-12-29"
}, {
"nome": "pessoa2",
"data_nascimento": "2021-12-29"
}, {
"nome": "pessoa3",
"data_nascimento": "2021-12-29"
}]
}
}]
}
}我已经对visita进行了一个展开和分组,这样我就有了一个visita文档。在我遇到问题的地方,查询如下:计算年龄介于以下范围内的人数:
0-2岁-9
2-4 - 0,
等
我用MongoDb罗盘进行了查询,下面的图像是我到现在为止的代码

发布于 2022-01-22 05:03:04
您可以使用$facet对传入的数据进行分类。
db.collection.aggregate([
{ "$unwind": "$visita" },
{ "$unwind": "$visita.pessoas.pessoa" },
{
"$project": {
years: {
"$dateDiff": {
"startDate": { "$toDate": "$visita.pessoas.pessoa.data_nascimento" },
"unit": "year",
"endDate": "$$NOW"
}
}
}
},
{
"$facet": {
"0-2-years": [
{
$match: {
$expr: {
"$and": [
{ $gte: [ "$years", 0 ] },
{ "$lt": [ "$years", 2 ] }
]
}
}
}
],
"2-4-years": [
{
$match: {
$expr: {
"$and": [
{ $gte: [ "$years", 2 ] },
{ "$lt": [ "$years", 4 ] }
]
}
}
}
]
}
},
{
$project: {
"0-2-years": { $size: "$0-2-years" },
"2-4-years": { $size: "$2-4-years" }
}
}
])Working 蒙戈游乐场
https://stackoverflow.com/questions/70809316
复制相似问题