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

123
Views
mongoose nested array filter

I have a document form similar to this

{
  "doc-id":2,
  "interfaces": [
    {
     
      "interface-role": "ON",
      "port-nb": 1
    },
    {
      
      "interface-role": "OFF",
      "port-nb": 2
    },
    {
      
      "interface-role": "ON",
      "port-nb": 3
    },
    {
      "interface-role": "OFF",
      "port-nb": 3
    }
  ]
}

I want to query and get specific document interfaces and also have the ability to filter ON and OFF and that's what I did try so far

   const doc = await this.doc
        .findOne({
          'doc-id': docId,
          'interfaces["interface-role"]': interfaceRole, //ON or OFF
        })
        .select({ interfaces: 1, _id: 0 })
        .exec();

so the result that I want to have is getting interfaces if there's no filter for interfaces-role and if there's one get the interfaces filtered

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use a $or to do the conditional filtering with a $filter.

db.collection.aggregate([
  {
    $match: {
      "doc-id": 2
    }
  },
  {
    "$addFields": {
      "interfaces": {
        "$filter": {
          "input": "$interfaces",
          "as": "i",
          "cond": {
            $or: [
              {
                $eq: [
                  null,
                  <interfaceRole>
                ]
              },
              {
                $eq: [
                  "$$i.interface-role",
                  <interfaceRole>
                ]
              }
            ]
          }
        }
      }
    }
  }
])

Here is the Mongo playground when interfaceRole is not supplied.

Here is the Mongo playground when interfaceRole is supplied.

about 4 years ago · Juan Pablo Isaza 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!