简体   繁体   中英

Fetch data from mongodb in three different field according to condition

i have a User collection having structure as below

{
    "_id" : ObjectId("596845524e20b8328d61b01f"),
    "created_at" : ISODate("2017-07-10T04:15:14.327Z"),
    "status" : 1,
    "updated_at" : ISODate("2017-08-22T07:29:44.000Z"),
    "is_activated" : 0,
    "totalrating" : 0,
    "is_admin" : 0,
    "basic_detail" : {
        "first_name" : "c",
        "last_name" : "f",
        "password" : "$2a$10$.WG",
        "user_type" : 1,
        "full_name" : "c f"
    }
},
    {
    "_id" : ObjectId("596845524e20b8328d61b01d"),
    "created_at" : ISODate("2017-07-10T04:15:14.327Z"),
    "status" : 1,
    "updated_at" : ISODate("2017-08-22T07:29:44.000Z"),
    "is_activated" : 0,
    "totalrating" : 0,
    "is_admin" : 0,
    "basic_detail" : {
        "first_name" : "c",
        "last_name" : "f",
        "user_type" : 2,
        "full_name" : "c f"
    }
},
    {
    "_id" : ObjectId("596845524e20b8328d61b01g"),
    "created_at" : ISODate("2017-07-10T04:15:14.327Z"),
    "status" : 1,
    "updated_at" : ISODate("2017-08-22T07:29:44.000Z"),
    "is_activated" : 0,
    "totalrating" : 0,
    "is_admin" : 0,
    "basic_detail" : {
        "first_name" : "c",
        "last_name" : "f",
        "user_type" : 3,
        "full_name" : "c f"
    }
}

i want to fetch data through aggreagte query and want data like below

{
   "totaluser":3,
   "totalho":1,//all those record having user_type=1,
   "totaltr":2,//all those record having user_type=2, 
   "totalcf":3,//all those record having user_type=3 
}

trying to do same with the help of group but not able to do please help I am using mongodb 3.4

[{ $facet:
   {
      totaluser: [ { $count: "totaluser" } ],
      totalho: [ {$match:{"basic_detail.user_type":1}},{ $count: "totalho" }],
      //other fields

   }
 },
{

$addFields:{
"totaluser": {
    $let:{
      vars:{totaluserObj:{ $arrayElemAt: [ "$totaluser", 0 ] }},
      in:"$$totaluserObj.totaluser"
    }
},
    "totalho": {
    $let:{
      vars:{totalhoObj:{ $arrayElemAt: [ "$totalho", 0 ] }},
      in:"$$totalhoObj.totalho"
    }
}
}
}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM