2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

how to search the count of matching element in a collection array of mongodb

how to search the count of matching element in a collection array of mongodb.

I have collection Named "TEST" which have lots of document.

Every collection have some FRUIT Name as key.

for e.g:

{
        "_id" : "05556-2b8-48cb-978f-91c7604ea5",
        "Data" : "Test date",
        "FRUIT" : [
                "Apple", "Mango"
        ]
}
{
        "_id" : "05556-2b8-48cb-978f-91c7604ea5",
        "Data" : "Test date",
        "FRUIT" : [
                "Grapes", "Mango"
        ]
}

Now i want to find number of records present in my collection having FRUIT , Mango?

userimage

To get the result in count, find the below query which will give the count of document having Mango as FRUIT.

db.TEST.find({FRUIT:{$elemMatch:{$eq:"Mango"}}}).count();

Answer is