I have documents with similar values of fields I want to get max times repeated values from documents

Viewed 27

Consider the following data:

{ 
  "_id" : ObjectId("61e14ce9d1cb1903c6158068"),
  "quesOne" : 1, 
  "quesTwo" : 2,
  "quesThree" : 3, 
  "quesFour" : 2, 
  "quesFive" : 2, 
  "quesSix" : 3, 
  "quesSeven" : 1, 
  "quesEight" : 4, 
  "quesNine" : 3, 
  "quesTen" : 4
}

I want output like: total 10 ques

Value times
4 2
3 3
2 3
1 2

Max count of value 2 & 3

2nd doc:

{ 
  "_id" : ObjectId("61dfd0e0d1cb196f0b9473da"), 
  "quesOne" : 2, 
  "quesTwo" : 2,
  "quesThree" : 4, 
  "quesFour" : 2, 
  "quesFive" : 4, 
  "quesSix" : 3, 
  "quesSeven" : 4, 
  "quesEight" : 4, 
  "quesNine" : 3, 
  "quesTen" : 4
}

output: total 28 ques

Value times
4 5
3 2
2 3
1 0

Max count of value 4

Is this possible with MongoDB query aggregations?

1 Answers

You can use $objectToArray to convert the $$ROOT object to an array of k-v tuple for process first. Then $unwind the array and $group by v to do the grouped count.

db.collection.aggregate([
  {
    $match: {
      "_id": ObjectId("61e14ce9d1cb1903c6158068")
    }
  },
  {
    $project: {
      _id: 0
    }
  },
  {
    $project: {
      arr: {
        "$objectToArray": "$$ROOT"
      }
    }
  },
  {
    "$unwind": "$arr"
  },
  {
    $group: {
      _id: "$arr.v",
      count: {
        $sum: 1
      }
    }
  }
])

Here is the Mongo playground for your reference.

Related