Search code examples
mongodbnosqldistinct

How to return another field and distinct field from mongodb distinct


Hello guys I want to ask, how can I return another field in the result of distinct mongodb method?

For example, I have the following documents:

[
    {
        "id": 1,
        "segment": "AAS",
        "partner": {}
    },
    {
        "id": 2,
        "segment": "AAS",
        "partner": {}
    },
    {
        "id": 3,
        "segment": "BBS",
        "partner": {}
    },
    {
        "id": 4,
        "segment": "CCS",
        "partner": {}
    },
    {
        "id": 5,
        "segment": "DDS",
        "partner": {}
    }
]

I want to distinct the segment field, but, I need to return the partner field too:

[
    {
        "segment": "AAS",
        "partner": {}
    },
    {
        "segment": "BBS",
        "partner": {}
    },
    {
        "segment": "CCS",
        "partner": {}
    },
    {
        "segment": "DDS",
        "partner": {}
    }
]

How can I produce that? Is it possible to use mapReduce method? how can I implement that?

Thank you!


Solution

  • Assume that you don't care about which AAS you get. I pick the first one.

    db.collection.aggregate([
      {
        $group: {
          _id: "$segment",
          field: {
            $first: "$$ROOT"
          }
        }
      },
      {
        $replaceWith: "$field"
      },
      {
        $unset: [ "id", "_id" ]
      }
    ])
    

    mongoplayground