Avinash
Avinash

Reputation: 147

Find min and max value from the array in mongodb

I have Following Project Collection

Project Collection :

[
{
    Id : 1,
    name : p1,
    tasks : [{
        taskId : t1,
        startDate : ISODate("2018-09-24T10:02:49.403Z"),
        endDate : ISODate("2018-09-26T10:02:49.403Z"),
    },
    {
        taskId : t2,
        startDate : ISODate("2018-09-24T10:02:49.403Z"),
        endDate : ISODate("2018-09-29T10:02:49.403Z"),
    },
    {
        taskId : t3,
        startDate : ISODate("2018-09-24T10:02:49.403Z"),
        endDate : ISODate("2018-09-27T10:02:49.403Z"),
    }]
}
]

How to get p1 project's startDate and EndDate depending on task execution i.e min start date and max endDate in task array

Example. P1 project contain 3 different task with different date I just want to get final start date and end date for project p1

Output should be
result : [{
  Id : 1,
  name : p1,
  startDate : ISODate("2018-09-24T10:02:49.403Z"), //min date 
  endDate : ISODate("2018-09-29T10:02:49.403Z") //max date
}]

Upvotes: 2

Views: 2298

Answers (1)

Ashh
Ashh

Reputation: 46461

You can try below query using $max aggregation operator.

db.collection.aggregate([
  { "$project": {
    "name": 1,
    "startDate": { "$min": "$tasks.startDate" },
    "endDate": { "$max": "$tasks.endDate" }
  }}
])

Output

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "endDate": ISODate("2018-09-29T10:02:49.403Z"),
    "name": "p1",
    "startDate": ISODate("2018-09-24T10:02:49.403Z")
  }
]

Upvotes: 3

Related Questions