簡體   English   中英

根據條件從mongodb的三個不同字段中獲取數據

[英]Fetch data from mongodb in three different field according to condition

我有一個用戶集合,其結構如下

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM