1

I try to query my events by their dates. So every event has a start date and a end date.

The structure of my Collection where these Events are inside is the following:

 {
    "_id": "5f2a7feae0c4e10017308fe5",
    "events": [
        {
            "_id": "5f2a802ce0c4e10017308fe8",
            "end": {
                "dateTime": "2020-08-05T23:46:00.000Z"
            },
            "start": {
                "dateTime": "2020-08-05T22:46:00.000Z"
            }
        }, ...
    ]
}

So I tried the following Aggregation Method:

The start and end values are ISO-Strings which are in my case the beginning and the end of an year.

   Collection.aggregate([
    { $match: {owner: owner_id}},
    {$unwind: '$events'},
    {  $match : 
      { 'events.start.dateTime': 
        {$gte: start, 
        $lt: end
        }
      }
    }, 
    {$sort: {'events.start.dateTime': 1}}, 
    {$group: {_id: '$_id', 'events': {$push: '$events'}}}
])

When I try it with the $match filter I get an empty Array back. But if I try it without the $match filter. I get all events from the collection back.

Does someone know where the problem could be?

NilsKyuubi
  • 351
  • 5
  • 15
  • you can match directly in $match check this https://mongoplayground.net/p/y135h4tmLvR and no need to $unwind and $group – turivishal Aug 05 '20 at 10:14
  • @turivishal I tried it with the the following $match query but it's still not working. – NilsKyuubi Aug 05 '20 at 10:22
  • { $match: { $and: [ {owner: owner_id}, { 'events.start.dateTime': {$gte: start, $lt: end } } ] } }, – NilsKyuubi Aug 05 '20 at 10:22
  • so you have check your input variable values in console its correct or not. and i can not see owner field in your provided document in your question – turivishal Aug 05 '20 at 10:26
  • @NilsKyuubi Are you sure `dateTime` fields in your documents are strings and not ISO dates? If the `dateTime` field is indeed string then you can have a look here: https://stackoverflow.com/questions/51647245/use-gte-and-lte-mongo-operator-if-date-is-in-string-format-in-mongodb. – Rahul Sharma Aug 05 '20 at 10:30
  • @RahulSharma dateTime is the {type: Date} in my MongoDB Collection – NilsKyuubi Aug 05 '20 at 10:36
  • 1
    Then I think using `ISODate` function to convert `start` and `end` variables to date should do the trick for you. https://stackoverflow.com/questions/31071999/date-comparison-in-mongodb/48615758 – Rahul Sharma Aug 05 '20 at 10:45

1 Answers1

2

Actually the new Date('2020-06-17T10:03:46.000Z') did the trick for me.

So my query looks like the following:

Collection.aggregate([
    { $match: { $and: [ {owner: owner_id}, { 'events.start.dateTime': {"$gte": new Date(start), "$lt": new Date(end) } } ] } },
    {$unwind: '$events'}, 
    {$sort: {'events.start.dateTime': 1}}, 
    {$group: {_id: '$_id', 'events': {$push: '$events'}}}
NilsKyuubi
  • 351
  • 5
  • 15