Mongodb get unique values from two fields


If you have fields in mongo which has lots duplicate values, but you want to analysis it by getting unique then you can that as I done as follows.

You can use the distinct method to retrieve unique values from a specific field in a collection. The distinct method returns an array of distinct values for a specified field across all documents in a collection.

But here we want to get unique values from multiple fields, so we can do that using $setUnion , Here is the example I worked out, hope it will be useful if someone looking for the same.

<code class="">
        $project: {
            fieldOne: 1,
            fieldSecond: 1
        $group: {
            fieldOnes: {$setUnion:"$fieldOnes"},
            fieldSecond: {$setUnion:"$fieldSecond"}

Posted in MongoDB by .

About Gowri

I am professional web developer with 8+ years experience. PHP, jQuery, WordPress, Angular and Ionic are my key skills in web development. I am working with strong enthusiastic team with spirit. We provide all web related solution like HTML/CSS development, Web graphic design and Logo.