mongoDB中要填充的聚合问题

thtygnil  于 2023-05-06  发布在  Go
关注(0)|答案(1)|浏览(134)

事务模型中有许多信息是不需要的,例如,我们不知道事务是注册为经销商还是交付,如果是注册为经销商还是交付,则另一个为空

dealer: {
  type: SchemaTypes.ObjectId,
  ref: 'Dealer',
  required: false,
},
delivery: {
  type: SchemaTypes.ObjectId,
  ref: 'Delivery',
  required: false,
},

当我使用aggregate时,只返回同时具有dealer值和delivery的数据

const aggregate = [
{
  $lookup: {
    from: 'deliveries',
    localField: 'delivery',
    foreignField: '_id',
    as: 'delivery',
  },
},
 {
  $unwind:"$delivery",
  },
{
  $lookup: {
    from: 'dealers',
    localField: 'dealer',
    foreignField: '_id',
    as: 'dealer',
  },
},
{
  $unwind: '$dealer',
}]

因此,不返回任何数据如何进行聚合如果文档中有字段,则不存在也无所谓

cgh8pdjw

cgh8pdjw1#

你可以将$unwind设置为true,这样如果有一个空数组要展开,文档就不会被删除。这是一个mongoplayground demo

const aggregate = [
  {
    $lookup: {
      from: "deliveries",
      localField: "delivery",
      foreignField: "_id",
      as: "delivery",
      
    }
  },
  {
    $unwind: {
      path: "$delivery",
      preserveNullAndEmptyArrays: true
    }
  },
  {
    $lookup: {
      from: "dealers",
      localField: "dealer",
      foreignField: "_id",
      as: "dealer",
      
    }
  },
  {
    $unwind: {
      path: "$dealer",
      preserveNullAndEmptyArrays: true
    }
  }
]

相关问题