如何從mongodb中收集年齡組基礎資料,即有多少人是0-18、19-24、25-34、35
[
{
"_id": ObjectId("608be7c608c7de2367c89638"),
"status": true,
"gender": "Male",
"first_name": "Vinter",
"last_name": "R",
"dob": "1-2-1999"
},
{
"_id": ObjectId("608be7c608c7de2267c89639"),
"status": true,
"gender": "Male",
"first_name": "Ray",
"last_name": "Morgan",
"dob": "1-2-2015"
}....
]
查看 mongo 游樂場 https://mongoplayground.net/p/4ydNg9Plh6P
uj5u.com熱心網友回復:
有趣的問題!
感謝@Takis 和@YuTing。
@Takis 對
$bucket.@YuTing 的回答很好。
通過利用 MongoDB 提供的功能,認為這個答案更短。
$toDate - 將日期字串轉換為日期(4.0 以上版本支持)。
$dateDiff - 日期減法并獲得單位(版本5支持)。
$$CURRENT- 獲取當前迭代檔案的變數。用于添加到persons陣列欄位(通過$push)。
$switch-group根據條件顯示值(可選)。
db.collection.aggregate([
{
"$addFields": {
"age": {
$dateDiff: {
startDate: {
$toDate: "$dob"
},
endDate: "$$NOW",
unit: "year"
}
}
}
},
{
$bucket: {
groupBy: "$age",
// Field to group by
boundaries: [
0,
19,
25,
35
],
// Boundaries for the buckets
default: "Other",
// Bucket id for documents which do not fall into a bucket
output: {
// Output for each bucket
"count": {
$sum: 1
},
"persons": {
$push: "$$CURRENT"
}
}
}
},
{
$project: {
_id: 0,
group: {
$switch: {
branches: [
{
case: {
$lt: [
"$_id",
19
]
},
then: "0-18"
},
{
case: {
$lt: [
"$_id",
25
]
},
then: "19-24"
},
{
case: {
$lt: [
"$_id",
35
]
},
then: "25-34"
}
],
default: "35 "
}
},
count: 1,
persons: 1
}
}
])
示例 Mongo Playground
uj5u.com熱心網友回復:
用 $bucket
db.collection.aggregate([
{
$bucket: {
groupBy: {
"$subtract": [
{
$year: new Date()
},
{
$toInt: {
$substr: [
"$dob",
{
$subtract: [
{
$strLenCP: "$dob"
},
4
]
},
4
]
}
}
]
},
// Field to group by
boundaries: [
0,
19,
25,
35,
100
],
// Boundaries for the buckets
default: "Other",
// Bucket id for documents which do not fall into a bucket
output: {
// Output for each bucket
"count": {
$sum: 1
},
"artists": {
$push: {
"name": {
$concat: [
"$first_name",
" ",
"$last_name"
]
},
"age": {
"$subtract": [
{
$year: new Date()
},
{
$toInt: {
$substr: [
"$dob",
{
$subtract: [
{
$strLenCP: "$dob"
},
4
]
},
4
]
}
}
]
}
}
}
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/340249.html
