PineCone
PineCone

Reputation: 2343

How to count the number of documents in which an element of an object inside an array exists in a collection of Mongodb

I have a MongoDB collection called Cards containing structurally similar documents as illustrated below:

{
"_id" : ObjectId("mongoid"),
"userName": "Har109",
"array1" : [
    {
        "id" : "11",
        "name" : "hello world",            
    }
    {
        "id" : "21",
        "name" : "bye world",            
    }
],
 "array2" : [
    {
        "id" : "1",
        "name" : "titanic",            
    }
    {
        "id" : "2",
        "name" : "avatar",            
    }
],
 "array3" : [
    {
        "id" : "1",
        "name" : "The Alchemist",            
    }
    {
        "id" : "2",
        "name" : "What is Zero",            
    }
]
}     

I need to query: Count the number of Documents in the collection that matches "array1.id", which I then can do it for all other arrays (e.g. "array2.id", "array3.id")

What is the syntax for this kind of query in MongoDB Compass?

I tried: the pipeline to get all the documents where there is array1

 [{$count: 'array1'}]

But how do I add the condition of where array1.id = "11" to this pipeline on mongodb compass, where stages are done separately.

Upvotes: 0

Views: 5047

Answers (1)

user12582392
user12582392

Reputation:

Count the number of Documents in the collection that matches "array1.id"

To find how many documents contain array.id=x you can run:

db.collection.find({ "array1.id":"11" }).countDocuments()

Or using aggregation

db.collection.aggregate([
{ $match:{"array1.id":"11"} }, 
{ count:"array1" }
])

The algorithm traverses arrays automatically.

It won't find a document if the key does not exist.

Upvotes: 0

Related Questions