Home > Enterprise >  HOW TO RETURN FULL DATA BUT UNIQUE IN CERTAIN FIELD
HOW TO RETURN FULL DATA BUT UNIQUE IN CERTAIN FIELD

Time:03-15

I have this example data

[
{id:1, type:"A", date:2022-01-01},
{id:2, type:"A", date:2022-01-02},
{id:3, type:"B", date:2022-01-01}
]

But how to get only one data per each type, like i have to get the output like this.

[
{id:2, type:"A", date:2022-01-02},
{id:3, type:"B", date:2022-01-01}
]

get only one data if have a same type value. i've tried $group $first but none work. any guys can help me? what should i code in mongodb?

CodePudding user response:

Not sure what not worked for you, but $group and $first (or $last) is the way to go, like so:

db.collection.aggregate([
  {
    $group: {
      _id: "$type",
      root: {
        $first: "$$ROOT"
      }
    }
  },
  {
    $replaceRoot: {
      newRoot: "$root"
    }
  }
])

Mongo Playground

  • Related