根据条件从三个不同的字段中获取mongodb中的数据

时间:2017-08-28 07:01:54

标签: mongodb

我有一个具有以下结构的用户集合

{
    "_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"
    }
}

我想通过aggreagte查询获取数据,并希望获得如下数据

{
   "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 
}

尝试在小组的帮助下做同样但不能做的请帮助我使用mongodb 3.4

1 个答案:

答案 0 :(得分:0)

[{ $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"
    }
}
}
}]