Home > Blockchain >  How can work on a field which is added in $project stage
How can work on a field which is added in $project stage

Time:02-25

I have this data in my database(only relative parts are provided here) :

[
  {
    "geojson": 5,
    "entity_status_update": "2021-12-28T10:16:58.000 00:00"
  },
  {
    "geojson": 7,
    "entity_status_update": "2021-12-03T10:16:58.000 00:00"
  },
  {
    "geojson": 2,
    "entity_status_update": "2021-11-08T10:16:58.000 00:00"
  }
]

I am trying to add a new field called deadline which should be equal to entity_status_update geojson days. I am using $dateAdd method of mongodb for the addition. My problem is I can't find a way to use days_to_add in my query. I think the reason is, it is in the $project stage yet.

[ 
  { 
    "$project": {
      "days_to_add": "$geo_json",                   // use this
      "deadline": {
        "$dateAdd": {
          "startDate": "$entity_status_update",
            "unit": "day",
            "amount": "$days_to_add"                // in here
        }
      }
    }
  }
]

How can I achieve this?

P.S. I must not directly use geojson in the calculation.

CodePudding user response:

you can add days_to_add using $addFields and then use it in your $project stage

mongoplayground

db.collection.aggregate([
  {
    "$addFields": {
      "days_to_add": "$geojson"
    }
  },
  {
    "$project": {
      "days_to_add": 1,
      "deadline": {
        "$dateAdd": {
          "startDate": "$entity_status_update",
          "unit": "day",
          "amount": "$days_to_add"
        }
      }
    }
  }
])
  • Related