如何查找和分组不同的值并在mongoDb中计数?

时间:2017-05-17 07:13:13

标签: mongodb group-by

下面是我的架构..我需要用不同的'user_email'来获取my'file_id'(我将定义我的file_id)的计数..注意..不是file_id的计数,具有相似和不同的user_email我只需要我的file_id的计数与不同的user_email.any帮助?

{
    "_id" : ObjectId("591bedc8c942a3514ed09b24"),

    "file_id" : "58450c20b053dc426b935927",
    "description" : "get your output ready",
    "user_email" : "abc@gmail.com",
    "__v" : 0
}
{
    "_id" : ObjectId("591bedc8c942a3514ed09b25"),

    "description" : "get your output ready",
    "user_email" : "abc@gmail.com",
    "__v" : 0
}
{
    "_id" : ObjectId("591bedc8c942a3514ed09b26"),

    "file_id" : "58450c20b053dc426b935927",
    "description" : "get your output ready",
    "user_email" : "hgi@gmail.com",
    "__v" : 0
}
{
    "_id" : ObjectId("591bedc8c942a3514ed09b27"),

    "file_id" : "58450c20b053dc426b935927",
    "description" : "get your output ready",
    "user_email" : "rfd@gmail.com",
    "__v" : 0
}
{
    "_id" : ObjectId("591beea4a62559b4506549e0"),

    "file_id" : "58450c20b053dc426b935927",
    "description" : "get your output ready",
    "user_email" : "negan@gmail.com",
    "__v" : 0
}



db.myschema.aggregate({$group:{"file_id":"58450c20b053dc426b935927","user_email" : "abc@gmail.com",count: { $sum: 1 }} })

1 个答案:

答案 0 :(得分:1)

以下查询应该为您提供file_iduser_email

的唯一计数
db.myschema.aggregate([

{
  $group: {
    _id: {"file_id": "$file_id", "user_email": "$user_email"},
    count: {$sum: 1}
  }
},
{

    $project: {
    _id: 0,
    "user_email": "$_id.user_email",
    "file_id": "$_id.file_id",
    "count": 1
    }

}

]);

修改 因此,如果您对特定file_id感兴趣,那么您只需按如下方式过滤结果:

let fileId = '58450c20b053dc426b935927';

db.myschema.aggregate([
  {
    $group: {
      _id: { file_id: "$file_id", user_email: "$user_email" },
      count: { $sum: 1 }
    }
  },
  {
    $match: {
      "_id.file_id": fileId
    }
  },
  {
    $project: {
      _id: 0,
      user_email: "$_id.user_email",
      file_id: "$_id.file_id",
      count: 1
    }
  }
]);