How do I FILTER returned data between two dates from mongodb using an aggregation : match, lookup and project?

后端 未结 1 1970
既然无缘
既然无缘 2021-01-17 03:31

I would like to get all Notifications between a start and end date that are related to a Register when I pass in a userId.

Register Schema



        
相关标签:
1条回答
  • 2021-01-17 03:51

    Your solution looks almost right, provided that dateStart and dateStart are actually Date objects and not Strings.

    Your Try 2 was incomplete I'm not sure it uses the $lookup from Try 1 or not. If so you have to make sure the output of $lookup is the same as input of $filter. So you should change as in $lookup to match input of $filter

    {
      $lookup: {
        from: "notifications",
        localField: "accessToken",
        foreignField: "accessToken",
        as: "items" // here
      }
    
    }
    

    Alternative Solution

    I'm not sure what you want as output. If you only need array of notifications without the user object, you can try the following.

    [{
      $match: { userId: mongoose.Types.ObjectId(userId) }
    }, {
      $lookup: {
        from: "notifications",
        localField: "accessToken", // don't forget to index register.accessToken
        foreignField: "accessToken", // don't forget to index notification.accessToken
        as: "notifications"
      }
    }, {
      $unwind: "$notifications"
    }, {
      $match: { 
        dateCreated: { $gte: dateStart, $lte: dateEnd } // dateStart, dateEnd should be Date objects
      }
    }, { // optional, move notifications to top lvel
      $replaceRoot: { root: '$notifications' }
    }]
    
    0 讨论(0)
提交回复
热议问题