Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Querying distinct values for an array per document

I have a collection with a bunch of documents, for example

{ items: [ObjectId1, ObjectId2, etc.] }

How do I run a query to identify which documents have duplicates? .distinct returns distinct values across the collection, but I want to be able to report on per document:

  1. the length/size of items
  2. the length/size of the unique/distinct items

essentially, to understand which documents have duplicates in the items array.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use aggregation with $addToSet operator to have unique items in the set:

db.collection.aggregate([
  {
    "$unwind": "$items"
  },
  {
    "$group": {
      "_id": "$_id",
      "items_cnt": {
        "$sum": 1
      },
      "unique_items": {
        "$addToSet": "$items"
      }
    }
  },
  {
    "$project": {
      "items_cnt": 1,
      "unique_items_cnt": {
        "$size": "$unique_items"
      }
    }
  }
])

playground

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!