How can I find distinct data in MongoDB after using find()

Prathmesh Bijjrgi Source

So I am getting this as output, I need only catalog_id as distinct as some of the catalog_id are duplicates.

db.catalog_product.find({product_id:{$in:["5a818d72590b65042559e2d4","5a818d9a590b65042649d966","5a81dd83590b65042559e2dd"]}},{catalog_id:true}).pretty();

    {
        "_id" : ObjectId("5a818d72590b65042559e2d5"),
        "catalog_id" : "5a8127ab590b65042649d942"
    }
    {
        "_id" : ObjectId("5a818d72590b65042559e2d6"),
        "catalog_id" : "5a8127ab590b65042649d942"
    }
    {
        "_id" : ObjectId("5a818d9a590b65042649d967"),
        "catalog_id" : "5a8127ab590b65042649d942"
    }
    {
        "_id" : ObjectId("5a818d9a590b65042649d968"),
        "catalog_id" : "5a8127ab590b65042649d942"
    }
    {
        "_id" : ObjectId("5a81dd83590b65042559e2de"),
        "catalog_id" : "5a813778590b65042649d94c"
    }
mongodb

Answers

answered 2 weeks ago Nilesh Singh #1

Why don't you try aggregate? You can group items based on a key i.e all distinct. Sample query would look like,

db.catalog_product.aggregate([
        {$match: {product_id: {$in:["5a818d72590b65042559e2d4","5a818d9a590b65042649d966","5a81dd83590b65042559e2dd"]}},
        {"$group": { "_id": "$catalog_id", "cid": {$first: "$_id"} }, //distinct here
        {$project: { "_id": '$cid', "catalog_id": "$_id"}}
]).pretty();

Note: This is an alternate aggregate way to find distinct items. Go with veeram's solution in the comments if you're looking for a cleaner way.

comments powered by Disqus