user8832254
user8832254

Reputation:

Count of a nested value of all entries in mongodb collection

I have a collection named outbox which has this kind of structure

"_id" :ObjectId("5a94e02bb0445b1cc742d795"),
"track" : {
    "added" : {
        "date" : ISODate("2020-12-03T08:48:51.000Z")
    }
},
"provider_status" : {
    "job_number" : "",
    "count" : {
        "total" : 1,
        "sent" : 0,
        "delivered" : 0,
        "failed" : 0
    },
    "delivery" : []
}

I have 2 tasks. First I want the sum of all the "total","sent","failed" on all the entries in the collection no matter what their objectId is. ie I want sum of all the "total","sent","delivered" and "failed". Second I want all these only for a given object Id between Start and End date. I am trying to find total using this query

db.outbox.aggregate(
{ $group: { _id : null, sum : { $sum: "$provider_status.count.total" } } });

But I am getting this error as shown Error Image

Since I do not have much experience in mongodb I don't have any idea how to do these two tasks. Need help here.

Upvotes: 1

Views: 282

Answers (1)

Gibbs
Gibbs

Reputation: 22956

You are executing this in Robo3t seems like.

You need to enclose this in an array like

db.test.aggregate([ //See here
  {
    $group: {
      _id: null,
      sum: {
        $sum: "$provider_status.count.total"
      }
    }
  }
])//See here

But it's not the case with playground as they handle them before submitting to the server

Upvotes: 2

Related Questions