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

237
Views
Filtering and measuring mongodb nested array of objects

I have a document of this kind:

{
 _id: "123",
 arrayName: [
         { text: 'first', field: false},
         { text: 'second', field: true},
         { text: 'third', field: false}
            ]
}

Now I would like to my query to return the length of filtered arrayName to have only the objects where field === false.

I have tried many queries with db.collection.find({}) but I always receive the entire document and in the end and it count() => to 1.

Any suggestion? thanks

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use projection operator to achieve what you want.

Try this:

db.collection.find({
    _id : givenId ,
    "arrayName.field" : false
},{
    "arrayName.$":1
},function(err,result){
   if(!err){
       len = result.arrayName.length;
       //use len however you want.
   }
});

"arrayName.$":1 will select only the matched elements of the array. Then you can get the length of array with field:false

Hope this helps!

over 4 years ago · Santiago Trujillo Report

0

Another user already give you the right answer for your question using the plain Mongo query. But I think it won't have much because you are using Mongo with Meteor, so here I present you another way to solve your problem by using transform function in find command:

Collection.find({
  // ...
}, {
  transform(doc) {
    doc.filterArrayLength = doc.arrayName.filter(obj => obj.field === false).length;

    return doc;
  }
}).fetch();

With this command the result will be like:

[
  // ...
  {
    _id: "123",
    arrayName: [
      {
        text: 'first',
        field: false
      }, {
        text: 'second',
        field: true
      }, {
        text: 'third',
        field: false
      }
    ],
    filterArrayLength: 2
  }
]
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!