Home > Blockchain >  How do I find date difference based on a field value in MongoDB?
How do I find date difference based on a field value in MongoDB?

Time:04-01

I want to find the date difference in a collection but for the objects which matches a given condition. Any clue on how to achieve this.

Currently, I am using a query:

db.sales.aggregate([ {
    $project: {
       item: 1,
       dateDifference: {
          $subtract: [ "$enddate", "$startdate" ]
       }
    }
} ])

but this will return the date difference for all of my objects in the collection.

I want to have something like say I have a items field and there are multiple items say Car, Bike, Cycle etc. Now i only want the date difference based upon the item value.

CodePudding user response:

Use $expr and $dateDiff

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gt: [
          {
            $dateDiff: {
              startDate: "$startdate",
              endDate: "$enddate",
              unit: "minute"
            }
          },
          20
        ]
      }
    }
  }
])

mongoplayground


db.collection.aggregate([
  {
    $match: { item: { $in: [ "Car", "Truck" ] } }
  },
  {
    $set: {
      diff: {
        $dateDiff: {
          startDate: "$startdate",
          endDate: "$enddate",
          unit: "minute"
        }
      }
    }
  }
])

mongoplayground

CodePudding user response:

say we have 4 sessions in a collection with properties like: Object1:
_id: 112233 item: CAR startdate: 2022-03-16 07:38:08.466Z enddate: 2022-03-16 08:38:08.466Z

Object2:
_id: 11222333 item: BIKE startdate: 2022-02-16 07:38:08.466Z enddate: 2022-02-14 08:38:08.466Z

Object3:
_id: 1122333243 item: CAR startdate: 2022-01-16 07:38:08.466Z enddate: 2022-02-16 01:38:08.466Z

Object4:
_id: 12312233 item: BUS startdate: 2021-03-16 07:38:08.466Z enddate: 2021-03-16 08:38:08.466Z

Now i want to find the difference of startdate and enddate say for CAR only.

  • Related