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
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!
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
}
]