Awadhesh Kumar
Awadhesh Kumar

Reputation: 420

How to get distinct values from MongoDB?

I am new in MongoDB and troubling to get distinct values from there.

This is documents in collection, where I want to distinct by "CustomerAccountNo" (this is duplicate values = 165)

   {
        "_id": "5e3eaf3ef5aab73568bd8494",
        "CustomerAccountNo": "123",
        "Customer": "Lucy Thom"
    },
    {
        "_id": "5e3eaf40f5aab73568bd8495",
        "CustomerAccountNo": "325",
        "Customer": "Nick Granger"
    },
    {
        "_id": "5e3eaf42f5aab73568bd8496",
        "CustomerAccountNo": "658",
        "Customer": "Tommy Tee"
    },
    {
        "_id": "5e3eaf44f5aab73568bd8497",
        "CustomerAccountNo": "6513",
        "Customer": "Carlos Nolasco"
    },
    {
        "_id": "5e3eaf49f5aab73568bd8498",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    },
    {
        "_id": "5e4660e9f57ea925a42b4ba2",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    }

And want the output like:

    {
        "_id": "5e3eaf3ef5aab73568bd8494",
        "CustomerAccountNo": "123",
        "Customer": "Lucy Thom"
    },
    {
        "_id": "5e3eaf40f5aab73568bd8495",
        "CustomerAccountNo": "325",
        "Customer": "Nick Granger"
    },
    {
        "_id": "5e3eaf42f5aab73568bd8496",
        "CustomerAccountNo": "658",
        "Customer": "Tommy Tee"
    },
    {
        "_id": "5e3eaf44f5aab73568bd8497",
        "CustomerAccountNo": "6513",
        "Customer": "Carlos Nolasco"
    },
    {
        "_id": "5e3eaf49f5aab73568bd8498",
        "CustomerAccountNo": "165",
        "Customer": "Hungarian Pastry shop"
    }

And i am trying the below code to get the above response,

collectionName.distinct("CustomerAccountNo") 

or

collectionName.aggregate([
  { $group: { _id: { CustomerAccountNo: "$CustomerAccountNo", Customer: "$Customer" } } }
]);

but both the above code not archive the correct response as I want, and I don't know what I am doing wrong.

Upvotes: 1

Views: 115

Answers (1)

prasad_
prasad_

Reputation: 14287

This aggregation will get the required result:

db.test.aggregate( [
  { $group: { _id: "$CustomerAccountNo", doc: { $first: "$$ROOT" } } },
  { $replaceRoot: { newRoot: "$doc" } }
] ).pretty()

Upvotes: 3

Related Questions