Anji
Anji

Reputation: 67

How to count array duplicate elements in MongoDB

in MongoDB data has the following prepare aggregate function 1

{"_id" : { "monthDate":"04-03-2020"}, "Job" : [ "Designer","Tester","Designer"]} 
{"_id" : { "monthDate":"14-03-2020"}, "Job" : [ "Designer","Tester","Tester"]} 
{"_id" : { "monthDate":"24-03-2020"}, "Job" : [ "Developer","Manager"]} 
{"_id" : { "monthDate":"25-03-2020"}, "Job" : [ "Developer","Developer","Developer"]} 

I need the following output

{"_id" : { "monthDate":"04-03-2020"}, "Job" : [ "Designer":2,"Tester":1]} 
{"_id" : { "monthDate":"14-03-2020"}, "Job" : [ "Designer":1,"Tester":2]} 
{"_id" : { "monthDate":"24-03-2020"}, "Job" : [ "Developer":1,"Manager":1]} 
{"_id" : { "monthDate":"25-03-2020"}, "Job" : [ "Developer":3]} 

Upvotes: 2

Views: 564

Answers (1)

turivishal
turivishal

Reputation: 36104

You can try,

  • $setUnion will get unique array from Job array
  • $map to iterate loop of unique array from above operation
  • $filter to get matching tag from main Job array and $size will get count of total matching tags from filter
  • $arrayToObject convert k(key) and v(value) format to object format
db.collection.aggregate([
  {
    $addFields: {
      Job: {
        $arrayToObject: {
          $map: {
            input: { $setUnion: "$Job" },
            as: "j",
            in: {
              k: "$$j",
              v: {
                $size: {
                  $filter: {
                    input: "$Job",
                    cond: { $eq: ["$$this", "$$j"] }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
])

Playground

Upvotes: 1

Related Questions