Get unique number of reservation based on dates

天涯浪子 提交于 2019-12-11 00:58:54

问题


How can I get unique booking counter? Like If I pass from date as "1970-01-01" and to date as "1970-01-05" then it will return me only 1. Because there is two booking but that's on different date (One is from 1970-01-01 to 1970-01-02 and another is from "1970-01-03" to "1970-01-05").

Reserved array contains all the booked rooms with from to to dates

Here is my data:

[
  {
    "_id": "5c0a17013d8ca91bf4ee7885",
    "name": "ABC",
    "reserved": [
      {
        "from": "1970-01-01",
        "to": "1970-01-02",
        "isCompleted": false
      },
      {
        "from": "1970-01-03",
        "to": "1970-01-05",
        "isCompleted": false
      },
      {
        "from": "2017-04-18",
        "to": "2017-04-23",
        "isCompleted": false
      },
      {
        "from": "2018-01-29",
        "to": "2018-01-30",
        "isCompleted": false
      }
    ]
  }
]

I've tried to get count using this query but it returns all the count not unique.

db.collection.aggregate([
    { $unwind: "$reserved" },
    {
        $match: { "reserved.from": { $lte: to }, "reserved.to": { $gte: from  } }
    },
    {
        $count: "total"
    }
])

EDIT-1

I don't want unique _id. Like you see inside reservation array there is two booking from date "1970-01-01" to "1970-01-05" (i.e One for "1970-01-01" to "1970-01-02" and another was "1970-01-03" to "1970-01-05") but both are not on same date. so when I query it will give me 2 as a count. But actually it was only one as per my requirement Because I want to count how many unique bookings done with in time period that I pass as query. See the below example

So, If my reserved array was like this then it will give me count 1 as a output For (pass from date as "1970-01-01" and to date as "1970-01-05") query

"reserved": [
      {
        "from": "1970-01-01",
        "to": "1970-01-02",
        "isCompleted": false
      },
      {
        "from": "1970-01-03",
        "to": "1970-01-05",
        "isCompleted": false
      }
]

And, If my reserved array was like this then it will give me count 2 as a output For (pass from date as "1970-01-01" and to date as "1970-01-05") query

"reserved": [
      {
        "from": "1970-01-01",
        "to": "1970-01-02",
        "isCompleted": false
      },
      {
        "from": "1970-01-03",
        "to": "1970-01-05",
        "isCompleted": false
      },
      {
        "from": "1970-01-03",
        "to": "1970-01-05",
        "isCompleted": false
      }
]

来源:https://stackoverflow.com/questions/54322947/get-unique-number-of-reservation-based-on-dates

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