在mongo汇总中查找后排除空的Forgien记录

时间:2019-09-17 09:20:43

标签: mongodb aggregate lookup

我在下面使用的以下代码返回下周发生的活动的组织列表。

const today = new Date()
const weekAfter = new Date()
weekAfter.setDate(weekAfter.getDate() + 7)

return Organizations.aggregate([
    {
      $lookup: {
        from: 'events',
        localField: '_id',
        foreignField: 'organizations.organizationId',
        as: 'eventsData'
      }
    },
    {
      $project: {
        name: 1,
        logo: 1,
        featuredImage: 1,
        startTime: 1,
        events: {
          $filter: {
            input: '$eventsData',
            as: 'event',
            cond: {
              $and: [
                { $gt: ['$$event.startTime', today] },
                { $lt: ['$$event.startTime', weekAfter] }
              ]
            }
          }
        }
      }
    }
  ]).exec()

我希望它只返回下周至少有一个活动的组织

我尝试了下面的代码,但是它仅将组织中没有任何关联的事件排除在外,而将空的事件包括在内,即使它们不在下周发生。

return Organizations.aggregate([
    {
      $lookup: {
        from: 'events',
        localField: '_id',
        foreignField: 'organizations.organizationId',
        as: 'eventsData'
      }
    },
    { 
      $unwind: {
        path: "$eventsData",
        preserveNullAndEmptyArrays: false
      }
    }, 
    {
      $group: {
        _id : "$_id",
        name: { $first : "$name" },
        logo: { $first : "$logo" },
        featuredImage: { $first : "$featuredImage" },
        startTime: { $first : "$startTime" },
        eventsData: { $push: "$eventsData" }
      }
    },
    {
      $project: {
        name: 1,
        logo: 1,
        featuredImage: 1,
        startTime: 1,
        events: {
          $filter: {
            input: '$eventsData',
            as: 'event',
            cond: {
              $and: [
                { $gt: ['$$event.startTime', today] },
                { $lt: ['$$event.startTime', weekAfter] }
              ]
            }
          }
        }
      }
    }
  ]).exec()

https://mongoplayground.net/p/axMWKt2EN8C

处查看此正在运行的MongoDB查询

1 个答案:

答案 0 :(得分:0)

尝试一下:

return Organizations.aggregate([
    {
      $lookup: {
        from: 'events',
        localField: '_id',
        foreignField: 'organizations.organizationId',
        as: 'eventsData'
      }
    },
    {
      $project: {
        name: 1,
        logo: 1,
        featuredImage: 1,
        startTime: 1,
        events: {
          $filter: {
            input: '$eventsData',
            as: 'event',
            cond: {
              $and: [
                { $gt: ['$$event.startTime', today] },
                { $lt: ['$$event.startTime', weekAfter] }
              ]
            }
          }
        }
      }
    },
    {
      $match:{
        "events.0":{
          $exists:true
        }
      }
    }
  ]).exec()