skip to Main Content

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?

2

Answers


  1. use $match to filter the records you want then use $group to group by date

    test it here: playground

    db.collection.aggregate([
      {
        "$match": {
          "source": "here"
        }
      },
      {
        "$group": {
          "_id": "$date",
          "count": {
            "$sum": 1
          }
        }
      },
      {
        "$project": {
          "_id": 0,
          "date": "$_id",
          "count": 1
        }
      }
    ])
    
    Login or Signup to reply.
  2. you can use aggregation query for it.

    db.collection.aggregate([
    {$match:{source:'here'},
    {$addFields:{count:1}},
    {$group:{_id:'$date'
    ,totalDocuments:{$sum:"$count"}}
    }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search