Group by multiple values in mongodb with pymongo

Viewed 27

I have this query and i want to group by {"$dateToString": { "format": "%Y-%m-%d ", "date": "$first" } and "id13":"$samples.id13"

mydb1.mongodbbuckethour.aggregate([

    {
        "$match": {
            "first": {"$gte": datetime.strptime("2010-01-01 00:05:00", "%Y-%m-%d %H:%M:%S"),
                          "$lte" :datetime.strptime("2020-12-31 23:00:00", "%Y-%m-%d %H:%M:%S")}
        }
    },
    { "$unwind": "$samples" },
{
        "$match": {
            "first": {"$gte": datetime.strptime("2010-01-01 00:05:00", "%Y-%m-%d %H:%M:%S"),
                          "$lte" :datetime.strptime("2020-12-31 23:00:00", "%Y-%m-%d %H:%M:%S")}
        }
    },

{
        "$group": {
            "_id": {"$dateToString": { "format": "%Y-%m-%d ", "date": "$first" } ,"id13":"$samples.id13"}





        }
      },
    {
        "$project": {
            "_id": 0,
            "day":"$_id",

        }
    },
    {"$sort": {"day": -1}}
])

The output says: An object representing an expression must have exactly one field: { $dateToString: { format: "%Y-%m-%d ", date: "$first" }, id13: "samples.id13" } What am i doing wrong? Thanks in advance!

1 Answers

I believe the error comes from the usage of $dateToString, since that is an expression for whose containing object you cannot specify any further object keys. What you probably wanted to do is assign the $dateToString expression to a dedicated field, date in this example:

{"$group": {
    "_id": {
        "date": {"$dateToString": {"format": "%Y-%m-%d ", "date": "$first"}},
        "id13": "$samples.id13"
    }
}
Related