Find min and max value from the array in mongodb

限于喜欢 提交于 2019-12-11 10:25:41

问题


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
}]

回答1:


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")
  }
]


来源:https://stackoverflow.com/questions/52481011/find-min-and-max-value-from-the-array-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!