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=""> db.collections.aggregate([ { $project: { fieldOne: 1, fieldSecond: 1 } }, { $group: { _id:null, fieldOnes:{$push:"$fieldOne"}, fieldSecond:{$push:"$fieldSecond"}, } }, { $project:{ fieldOnes: {$setUnion:"$fieldOnes"}, fieldSecond: {$setUnion:"$fieldSecond"} } } ])</code>