1

My documents are organized this way:

{
        "_id" : ObjectId("5ea899d7e7da54cabbc022e7"),
        "date" : ISODate("2018-01-27T00:00:00Z"),
        "vehicleid" : 32028,
        "points" : [
                {
                        "direction" : 225,
                        "location" : {
                                "type" : "Point",
                                "coordinates" : [
                                        -3.801898,
                                        -38.501078
                                ]
                        },
                        "odometer" : 134746396,
                        "routecode" : 0,
                        "speed" : 0,
                        "deviceid" : 148590,
                        "metrictimestamp" : ISODate("2018-01-27T23:32:03Z")
                }

Where points is an array of objects. I need to group this documents and return the amount of elements inside each array. I guess that is something like:

pipe = [ 
  {
    '$project':{
      "_id":0
    }
  },
  {
    '$group':{
      "_id":{
        "vehicleid":"$vehicleid",
        "date":"$date"
      },'count':{'$size':'points'}
    }
  }
         ]

Detail: I need to run this on pymongo.

3
  • { '$size': 'points' } should be { '$size': '$points' } Commented Apr 29, 2020 at 22:32
  • pymongo.errors.OperationFailure: unknown group operator '$size', returns this error Commented Apr 29, 2020 at 23:03
  • It should be { 'count': { '$sum': { '$size': '$points' } } } Commented Apr 29, 2020 at 23:07

3 Answers 3

3

You have to use $sum to sum the size of each array like this

  {
    "$group": {
      "_id": {
        "vehicleid": "$vehicleid",
        "date": "$date"
      },
      "count": { "$sum": { "$size": "$points" } }
    }
  }
Sign up to request clarification or add additional context in comments.

Comments

1

You can use any of the following aggregation pipelines. You will get the size of the points array field. Each pipeline uses different approach, and the output details differ, but the size info will be same.

The code runs with PyMongo:

pipeline = [
    { 
        "$unwind": "$points" 
    },
    { 
        "$group": { 
            "_id": { "vehicleid": "$vehicleid", "date": "$date" }, 
            "count": { "$sum": 1 } 
        }
    }
]

pipeline = [
  { 
      "$addFields": { "count": { "$size": "$points" } }
  }
]

Comments

0

You can follow this code

$group : {
       _id : {
        "vehicleid":"$vehicleid",
        "date":"$date"
         count: { $sum: 1 }
       }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.