MongoDB get individual count from sudocuments with comparison operations

冷暖自知 提交于 2020-01-23 17:27:06

问题


I am using mongoDB I use query

db.getCollection('managements').find({'managers.role':"HR"},{'managers.$':1})

I get result as below

/* 1 */
{
    "_id" : ObjectId("1"),
    "managers" : [ 
        {
            "id" : "100",
            "role" : "HR"
        },
        {
            "id" : "101",
            "role" : "ADMIN"
        },
        {
            "id" : "102",
            "role" : "ADMIN"
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("2"),
    "managers" : [ 
        {
            "id" : "104",
            "role" : "ADMIN"
        },
        {
            "id" : "105",
            "role" : "HR"
        }
        ,
        {
            "id" : "106",
            "role" : "HR"
        }
        ,
        {
            "id" : "107",
            "role" : "HR"
        }
    ]
}

Now I want to get individual records where role is HR and count is more than one, like

{ id:2
count : 3}

回答1:


You can use below aggregation

db.collection.aggregate([
  { "$match": {
    "$expr": {
      "$gte": [
        { "$size": {
          "$filter": {
            "input": "$managers",
            "cond": { "$eq": ["$$this.role", "HR"] }
          }
        }},
        2
      ]
    }
  }},
  { "$addFields": {
    "count": {
      "$size": {
        "$filter": {
          "input": "$managers",
          "cond": { "$eq": ["$$this.role", "HR"] }
        }
      }
    }
  }}
])


来源:https://stackoverflow.com/questions/59786240/mongodb-get-individual-count-from-sudocuments-with-comparison-operations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!