EN VI

Mongodb - Mongo count number of objects grouped by a field value?

2024-03-13 15:00:08
How to Mongodb - Mongo count number of objects grouped by a field value

I have the following mongo model:

{
    "_id" : "5f5a1c1f6976570001783ab7",
    "date" : NumberLong(1590624000),
    "source" : "here",
}

I would like to have the number of documents, group by date, that have source field at here value for example:

{
    "date" : NumberLong(1590624000),
    "count": 5
},

{
    "date" : NumberLong(1590710400),
    "count": 10
}

What mongo query should I use to have the following result?

Solution:

you can use aggregation query for it.

db.collection.aggregate([
{$match:{source:'here'},
{$addFields:{count:1}},
{$group:{_id:'$date'
,totalDocuments:{$sum:"$count"}}
}
])
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login