0

I want to find information that is on the same date.My Data is

[
  {
    "reservations": [],
    "_id": "5ff62f01d274650f5f187c00",
    "floorNumber": "floor 4",
    "sessionInDay": "morning",
    "start": "2021-01-10T00:00:00.000Z",
    "seatsAvailable": 15,
    "id": 1,
    "__v": 0
  },
  {
    "reservations": [],
    "_id": "5ff6346be9a69310deeeabc2",
    "floorNumber": "floor 4",
    "sessionInDay": "morning",
    "start": "2021-01-05T00:00:00.000Z",
    "seatsAvailable": 15,
    "id": 2,
    "__v": 0
  },
  {
    "reservations": [],
    "_id": "5ff6346be9a69310deeeabc2",
    "floorNumber": "floor 4",
    "sessionInDay": "afternoon",
    "start": "2021-01-05T00:00:00.000Z",
    "seatsAvailable": 15,
    "id": 3,
    "__v": 0
  }
]

I want to combine data with the same start date. To come out in what format? How do I query? The data format I want to output :

[
  {
    "start": "2021-01-10T00:00:00.000Z",
    "details": [
      {
        "reservations": [],
        "_id": "5ff62f01d274650f5f187c00",
        "floorNumber": "floor 4",
        "sessionInDay": "morning",
        "start": "2021-01-10T00:00:00.000Z",
        "seatsAvailable": 15,
        "id": 1
      }
    ]
  },
  {
    "start": "2021-01-05T00:00:00.000Z",
    "details": [
      {
        "reservations": [],
        "_id": "5ff6346be9a69310fad23413",
        "floorNumber": "floor 4",
        "sessionInDay": "morning",
        "start": "2021-01-05T00:00:00.000Z",
        "seatsAvailable": 15,
        "id": 2
      },
      {
        "reservations": [],
        "_id": "5ff6346be9a69310deeeabc2",
        "floorNumber": "floor 4",
        "sessionInDay": "afternoon",
        "start": "2021-01-05T00:00:00.000Z",
        "seatsAvailable": 15,
        "id": 3
      }
    ]
  }
]

The last question, this step. Should I format data like this, save it to the Database, or should I use the Query method?

Thank to help me.

Applesz
  • 15
  • 3

1 Answers1

1
  1. Finding all documents on same date ( example for 2021-01-10 ):
db.reservations.find({start:/^2021-01-10/})
  1. Combine data for the same start date:
db.reservations.aggregate([ 
  {$project:{date:{$substr:["$start",0,10]}, floorNumber:1,sessionDay:1,start:1,seatsAvailable:1 , id:1,"__v":1 ,_id:0 }} ,
  {$group:{_id:"$date" , details:{$push:"$$ROOT"}   }} , 
  {$project:{date:"$_id", _id:0 ,details:1} } 
])
  1. On the question if you need to format the data like in the aggregation result , it very depends on how you use the data , best in mongodb is to denormalize as much as possible and to have the data together in natural way same way as it will be shown , so if in 90% of the time you will query by date and show all reservations per day most of the time it maybe better to modify as in the aggregation result...
turivishal
  • 34,368
  • 7
  • 36
  • 59
R2D2
  • 9,410
  • 2
  • 12
  • 28