Home > Enterprise >  Find Mongo docs where a value is unique from all other documents using Mongoose
Find Mongo docs where a value is unique from all other documents using Mongoose

Time:10-12

Let's say I had a Schema called MyDoc with field key. These were my documents:

[
  {
    "key": 1
  },
  {
    "key": 2
  },
  {
    "key": 2
  },
  {
    "key": 3
  },
  {
    "key": 3
  },  
  {
    "key": 3
  },
  {
    "key": 4
  }

]

With mongoose, I want to find documents that have a unique key value. AKA return all docs where no other docs have its key value.

Above, there are multiple docs with 2 and 3. One document each has a value of 1 and 4. So in this example, I want to return only the document with 1 and 4.

CodePudding user response:

One options is via aggregation group:

db.collection.aggregate([
{
 $group: {
  _id: "$key",
  cnt: {
    $sum: 1
  }
  }
 },
 {
  $match: {
  cnt: {
    $eq: 1
  }
 }
 },
 {
 $project: {
  key: "$_id",
  _id: 0
 }
}
])

Stages explained:

  1. Group by key to count() the duplicates
  2. Match only those that have no duplicates
  3. Project only the needed keys

playground

  • Related