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

295
Views
How to filter an array of objects to remove elements based on condition in MongoDB aggregate?

I have a collection of documents ChatRooms in MongoDB that has this (simplified) structure:

{
  _id: ObjectId('4654'),
  messages: [
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-01T00:00:00.000Z')
    },
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-02T00:00:00.000Z')
    },
    {
      user: ObjectId('8888'),
      sentAt: ISODate('2022-03-03T00:00:00.000Z')
    },
  ]
}

What I'm trying to achieve is to filter the messages array inside the aggregate pipeline in order to get an array where the userId is presend just once. The result I'm looking for is (or something similar but the array shouldn't have two elements with the same user id):

{
  _id: ObjectId('4654'),
  messages: [
    {
      user: ObjectId('1234'),
      sentAt: ISODate('2022-03-01T00:00:00.000Z')
    },
    {
      user: ObjectId('8888'),
      sentAt: ISODate('2022-03-03T00:00:00.000Z')
    },
  ]
}

Is such a thing possible even? Any help would be much appreciated.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do this in several different ways, here is an example of how to achieve this using the $reduce operator:

db.collection.aggregate([
  {
    $addFields: {
      messages: {
        $reduce: {
          input: "$messages",
          initialValue: [],
          in: {
            $cond: [
              {
                $in: [
                  "$$this.user",
                  "$$value.user"
                ]
              },
              "$$value",
              {
                "$concatArrays": [
                  "$$value",
                  [
                    "$$this"
                  ]
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Mongo 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!