如果子数组中有条件,则Mongo聚合删除组

时间:2019-03-07 15:18:41

标签: mongodb aggregation-framework

在管道的某个位置,我具有这样的结构:

[
    {
        _id: 1,
        elems1: [{sub : {date: xxx}}, {sub: {date: yyy}}],
        elems2: [{sub: {date: zzz}}, {sub: {date: qqq}}]
    },
    ...
]

来自分组:

{$group: {
    _id: '$user.id',
    elems1: {
        $push: {sub: '$other'}
        },
    elems2: {
        $push: {sub: '$other'}
        }
    }
}}

现在,我要删除elems1少于elems2sub.date中具有某个元素的组,该怎么做?

1 个答案:

答案 0 :(得分:1)

当您执行$group时,还可以在下一个管道阶段中跟踪“ minElemDate”,然后跟踪$match

$group: {
  _id: "$user.id",
  elem1s: ...,
  elem2s: ...
  minElemDate: {
    $min: {
      $cond: [
        { $or: [condition1, condition2] },
       "$user.date",
        null
      ]
    }
  }
},
{ $match: {$gte: ["$minElemDate", minDate]} }