php - mongodb中按年龄组分组

标签 php mongodb mongodb-query aggregation-framework

我正在使用以下 mongo 数据库查询。它只向我显示我的角色数据的年龄组。

    db.amplifyindex.aggregate([
    { $unwind: "$demographic" },
    { $match : { 'demographic.is_latest':"active",        
    'demographic.date_of_birth' : { $exists : true} } },
    { $project : {"ageInMillis" : {$subtract : [new Date(),   
    "$demographic.date_of_birth"] } } }, 
    { $project : {"age" : {$divide : ["$ageInMillis", 31558464000] }}},
    { $project : {"age" : {$subtract : ["$age", {$mod : ["$age",1]}]}}},

     ])

此查询的结果对象是:

{
"_id" : ObjectId("58a42cbbdb5d880c1e000029"),
"age" : 29.0
 }

我想以如下方式获取数据:

{
"_id" : ObjectId("58a42cbbdb5d880c1e000029"),
"age" : 10-30
"personas" : 10
}

我的场景中的完整数据结构如下:

{
"_id" : ObjectId("58a42cbbdb5d880c1e000029"),
"persona_email" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f19c989d859e9fdf849d9d83989299b1969c90989ddf929e9c" rel="noreferrer noopener nofollow">[email protected]</a>",
"company_id" : "1",
"date_added" : ISODate("2017-02-15T10:23:15.000Z"),
"demographic" : [ 
    {
        "persona_fname" : "Hayden",
        "middle_name" : "Jacobs",
        "persona_lname" : "Schmeler",
        "gender" : "male",
        "date_of_birth" : ISODate("1987-06-16T19:00:00.000Z"),
        "marital_status" : "single",
        "height" : "2.1 feet",
        "weight" : "5 kg",
        "measurement" : {
            "waist" : "34 inch"
        },
        "disabilities" : "No",
        "race" : "Asian",
        "nationality" : "Jordan",
        "life_cycle" : "empty nest",
        "children" : {
            "gender" : "female",
            "date_of_birth" : ISODate("1987-06-16T19:00:00.000Z")
        },
        "medicare_no" : "4916725587565",
        "driving_licence_no" : "PACBALM420M",
        "id_no" : "4485872783336",
        "passport_no" : "OCRFHCNR",
        "residential_address" : {
            "unit_no" : 603,
            "street_no" : "34863 Ondricka Viaduct Apt. 154",
            "street_name" : "84799 Little Wall",
            "suburb" : "West Virginia",
            "postal_code" : "23873",
            "state" : "Dominica",
            "country" : "Cook Islands"
        },
        "work_address" : {
            "unit_no" : "6011865161287875",
            "street_no" : "630 Beer Underpass Suite 372",
            "street_name" : "87672 Lind Burg",
            "suburb" : "West Virginia",
            "postal_code" : "84356-3662",
            "state" : "Qatar",
            "country" : "British Indian Ocean Territory (Chagos Archipelago)"
        },
        "shipping_address" : {
            "unit_no" : "6011865161287875",
            "street_no" : "8292 Langosh Drive Suite 065",
            "street_name" : "9844 Nicolas Mount",
            "suburb" : "West Virginia",
            "postal_code" : "07014",
            "state" : "Togo",
            "country" : "Tunisia"
        },
        "job_title" : "Geoscientists",
        "employer_name" : "Aufderhar Group",
        "income" : 72577,
        "phone_numbers" : {
            "work_phone" : "993-783-7499",
            "home_phone" : "701.546.7016",
            "mobile" : "1-346-729-4392"
        },
        "emails" : {
            "work_emails" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5bbbcbebab9b4a0a6fbb4a6b495b2b8b4bcb9fbb6bab8" rel="noreferrer noopener nofollow">[email protected]</a>",
            "personal_emails" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e3868e8e8a9797d5dba3848e828a8fcd808c8e" rel="noreferrer noopener nofollow">[email protected]</a>"
        },
        "languages" : "italian",
        "data_source" : "soldi",
        "date_added" : ISODate("2017-02-15T10:23:15.000Z"),
        "source" : "soldi",
        "is_latest" : "inactive"
    },
    {
        "persona_fname" : "Julien",
        "middle_name" : "Hirthe",
        "persona_lname" : "Schaefer",
        "gender" : "female",
        "date_of_birth" : ISODate("1987-06-16T19:00:00.000Z"),
        "marital_status" : "single",
        "height" : "2.1 feet",
        "weight" : "5 kg",
        "measurement" : {
            "waist" : "34 inch"
        },
        "disabilities" : "No",
        "race" : "Asian",
        "nationality" : "Sudan",
        "life_cycle" : "single",
        "children" : {
            "gender" : "female",
            "date_of_birth" : ISODate("1987-06-16T19:00:00.000Z")
        },
        "medicare_no" : "4024007131689860",
        "driving_licence_no" : "OGOSUOIFSDN",
        "id_no" : "5523297913341227",
        "passport_no" : "WWZYTE489ZR",
        "residential_address" : {
            "unit_no" : 603,
            "street_no" : "338 Mueller Gardens Suite 397",
            "street_name" : "6302 Catalina Isle",
            "suburb" : "West Virginia",
            "postal_code" : "97534",
            "state" : "Antarctica (the territory South of 60 deg S)",
            "country" : "Turks and Caicos Islands"
        },
        "work_address" : {
            "unit_no" : "6011865161287875",
            "street_no" : "8561 Jesus Ridges Apt. 662",
            "street_name" : "1869 Josiah Wall Apt. 347",
            "suburb" : "West Virginia",
            "postal_code" : "14810",
            "state" : "Zambia",
            "country" : "Mongolia"
        },
        "shipping_address" : {
            "unit_no" : "6011865161287875",
            "street_no" : "514 Heller Center",
            "street_name" : "835 Paxton Cliffs Suite 040",
            "suburb" : "West Virginia",
            "postal_code" : "48942-3845",
            "state" : "Palau",
            "country" : "Belize"
        },
        "job_title" : "Geoscientists",
        "employer_name" : "Aufderhar Group",
        "income" : 72577,
        "phone_numbers" : {
            "work_phone" : "(553) 892-7614 x573",
            "home_phone" : "796.308.3001 x88799",
            "mobile" : "+1-876-339-1755"
        },
        "emails" : {
            "work_emails" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="29595b4641485a42480742485d4c455047476941465d44484045074a4644" rel="noreferrer noopener nofollow">[email protected]</a>",
            "personal_emails" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cfa0b5baa3aebaa98fa5aaa1a4a6a1bce1aca0a2" rel="noreferrer noopener nofollow">[email protected]</a>"
        },
        "languages" : "german",
        "data_source" : "soldi",
        "date_added" : ISODate("2017-02-15T10:23:15.000Z"),
        "source" : "soldi",
        "is_latest" : "active"
    }
]
  }

最佳答案

在您的组管道中,创建年龄范围作为 _id 键的一部分,这可以通过使用 $concat 来完成。 "$cond" 运营商。考虑运行以下管道以获得所需的结果:

db.amplifyindex.aggregate([
    { "$unwind": "$demographic" },
    { "$match": { "demographic.is_latest": "active" } },
    { 
        "$project": {
            "age": {
                "$divide": [
                    {
                        "$subtract": [
                            new Date(),
                            { "$ifNull": ["$demographic.date_of_birth", new Date()] }
                        ]
                    },
                    1000 * 86400 * 365
                ]
            }
        }
    },
    {
        "$group": {
            "_id": {
                "$concat": [
                    { "$cond": [ { "$lte": [ "$age", 0 ] }, "Unknown", ""] },
                    { "$cond": [ { "$and": [ { "$gt":  ["$age", 0 ] }, { "$lt": ["$age", 10] } ]}, "Under 10", ""] },
                    { "$cond": [ { "$and": [ { "$gte": ["$age", 10] }, { "$lt": ["$age", 31] } ]}, "10 - 30", ""] },
                    { "$cond": [ { "$and": [ { "$gte": ["$age", 31] }, { "$lt": ["$age", 51] } ]}, "31 - 50", ""] },
                    { "$cond": [ { "$and": [ { "$gte": ["$age", 51] }, { "$lt": ["$age", 71] } ]}, "51 - 70", ""] },
                    { "$cond": [ { "$gte": [ "$age", 71 ] }, "Over 70", ""] }
                ]
            },
            "personas": { "$sum": 1 }
        }
    },
    { "$project": { "_id": 0, "age": "$_id", "personas": 1 } }
 ])

在上面的管道中,我取出了对空日期字段的查询并将其替换为 $ifNull $project 中的 运算符 管道。这将返回生日字段为空的当前日期,从而产生 0 岁的年龄,该年龄将属于特殊的年龄范围括号,因此需要包含所有文档,包括出生日期字段缺失的文档。

$concat的情况下 运算符用于所有 $cond 表达式,该组合至关重要,因为它充当 case 语句,否则将出现嵌套 $cond 运营商。

要了解此设计,请采用第三个 $cond 表达

{ 
   "$cond": [ 
       { 
           "$and": [ 
               { "$gte": ["$age", 10] }, 
               { "$lt": ["$age", 31] } 
           ]
       }, 
       "10 - 30", // matching if
       ""  // else
   ] 
},

本质上表达了逻辑

if ( "$age" >= 10 && "$age" < 31 ) { return "10 - 30"; }
else return "";

<强> $concat $cond 一起使用时很有用。 运算符作为表达式将返回除匹配值之外的空值,而匹配值又将返回年龄组。

例如,将返回年龄 30.645411

"$concat": [ "", "", "10 - 30", "", "", "" ] 

然后为您提供一个 _id,其值为 “10 - 30”。

关于php - mongodb中按年龄组分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42435584/

相关文章:

php - 金额参数是必需的 - Omnipay paypal with laravel

php - Gmail 应用程序接口(interface)。如何获取消息标签

php - 电子商务是否从零开始

mysql - 仅当当前字段存在于数组中时如何对字段进行计数或求和

spring - 在 MongoDB for Spring 中查找/删除 @DBref 列表项

java - Vava 查询 MongoDB : find event in a specific date range

php - laravel 集合到数组

mongodb - 如何在 mongodb 的集合中添加一个新的数组字段?

node.js - net::ERR_CONNECTION_CLOSED 在 mongo 文档中有超过 7 个子文档时在远程服务器上

JavaScript 堆内存不足 - 插入 mongodb 时出错