Search code examples
mongodbdistinct

How to get multiple distinct fields in MongoDB?


I am using MongoDB with Nodejs. For example:

Array = [{name: 'Sam',  age: 26, hobby: 'Baseball'},
         {name: 'Sam',  age: 30, hobby: 'Baseball'},
         {name: 'John', age: 26, hobby: 'Baseball'},
         {name: 'Mike', age: 32, hobby: 'Baseball'},
         {name: 'Max',  age: 32, hobby: 'Baseball'},]
        
                                                    

I want a query which doesnt repeat any value of name and age and gives me result => [ {name: 'Sam', age: 26, hobby: 'Baseball'},{name: 'Mike', age: 32, hobby: 'Baseball'} ]

Is it possible to using MongoDB and Nodejs?

I checked distinct() but it only takes one filled as a query.


Solution

  • You can use $facet to categories name and age

    • $sort to sort by age
    • $facet to categorie incoming data into two groups. One is group by name and other one is group by age.
    • $setIntersection to get the common objects of two arrays. But please have a look on if the key order is changed

    The script is

    db.collection.aggregate([
      { $sort: { age: 1 } },
      {
        $facet: {
          nameGroup: [
            {
              $group: {
                _id: "$name",
                name: { $first: "$name" },
                age: { $first: "$age" },
                hobby: { $first: "$hobby" }
              }
            },
            { $project: { _id: 0 } }
          ],
          ageGroup: [
            {
              $group: {
                _id: "$age",
                name: { $first: "$name" },
                age: { $first: "$age" },
                hobby: { $first: "$hobby" }
              }
            },
            { $project: { _id: 0 } }
          ]
        }
      },
      {
        $project: {
          data: { "$setIntersection": [ "$nameGroup", "$ageGroup" ] }
        }
      }
    ])
    

    Working Mongo playground