Ask Your Question
3

How can I identify identical document values in a MongoDB collection using 2 fields?

asked 2023-06-11 18:17:47 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-06-11 18:40:02 +0000

pufferfish gravatar image

One way to identify identical document values in a MongoDB collection using 2 fields is to use the $group aggregation pipeline stage. For example, if we have a collection of documents with fields "name" and "age", we can use the following pipeline:

db.collection.aggregate([
  {
    $group: {
      _id: { name: "$name", age: "$age" },
      count: { $sum: 1 }
    }
  },
  {
    $match: {
      count: { $gt: 1 }
    }
  }
])

This pipeline groups documents by the "name" and "age" fields and counts the number of documents that have each unique combination of values. The $match stage filters out any groups that have a count of 1, leaving us with only the groups that have identical document values.

We can also include additional fields in the _id object to group by more than 2 fields, or add more stages to the pipeline to further filter or manipulate the results.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-11 18:17:47 +0000

Seen: 7 times

Last updated: Jun 11 '23