In Mongoose How to exclude documents that have common value in particular field but return first document only? In Mongoose How to exclude documents that have common value in particular field but return first document only? mongoose mongoose

In Mongoose How to exclude documents that have common value in particular field but return first document only?


You can use $group for grouping same values, and $replaceRoot for replace grouped documents from $group.

db.collection.aggregate([  // updated match/where conditions  {    $match: {      isRead: false,       isChat: true,       receiverBy: userId    }  },  {    $group: {      _id: "$createdBy",      root: {        $first: "$$ROOT"      }    }  },  {    $replaceRoot: {      newRoot: "$root"    }  }])

Working Playground: https://mongoplayground.net/p/qzyXuP-3nv8