Search code examples
mongodbmongodb-queryaggregation-frameworkaggregation

mongo use $add aggregation within an aggregation


I'm trying to add 1 day within an equality aggregation so the day+1 should be compared to the field modifiedAt which contains an ISODATE in my DB.

Unfortunately I'm unable to do this. error within mongodb compass is 'Field must not begin with $ or . field path was $add'


{"$match":
   {"$expr":
    {
      "$eq":["$modified",{"$add": [ISODate('xxx'),1*24*60*60000]}]}
    }

}

Solution

  • Your query seems to work as expected:

    mongos> db.f.find()
    { "_id" : ObjectId("60038464a2d94094f8a216bc"), "modified" : ISODate("2021-01-17T00:27:16.280Z") }
    { "_id" : ObjectId("6003853ca2d94094f8a216bd"), "modified" : ISODate("2021-01-17T02:27:16.280Z") }
    { "_id" : ObjectId("60038544a2d94094f8a216be"), "modified" : ISODate("2021-01-16T02:27:16.280Z") }
    { "_id" : ObjectId("6003855fa2d94094f8a216bf"), "modified" : ISODate("2021-01-18T02:27:16.280Z") }
    mongos> db.f.aggregate( [  {"$match":  {"$expr":  { "$eq":["$modified",{"$add": [ISODate("2021-01-17T02:27:16.280Z"),1*24*60*60000]}]}    } } ])
    { "_id" : ObjectId("6003855fa2d94094f8a216bf"), "modified" : ISODate("2021-01-18T02:27:16.280Z") }
    mongos>