0
votes

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?

1
you can match directly in $match check this mongoplayground.net/p/y135h4tmLvR and no need to $unwind and $group - turivishal
@turivishal I tried it with the the following $match query but it's still not working. - NilsKyuubi
{ $match: { $and: [ {owner: owner_id}, { 'events.start.dateTime': {$gte: start, $lt: end } } ] } }, - NilsKyuubi
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
Then I think using ISODate function to convert start and end variables to date should do the trick for you. stackoverflow.com/questions/31071999/date-comparison-in-mongodb/… - Rahul Sharma

1 Answers

1
votes

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