MongoDB: aggregation - 分组条件如果不为空

MongoDB: aggregation - group condition if not empty

如果有这样的数据:

{
 user: "max",
 uploaded: <timestamp>,
 updated: <timestamp>
}
{
 user: "tim",
 uploaded: <timestamp>
}

每个用户都可以拥有不同的项目。现在我将 mongoDB 聚合框架与 $match + $group 一起使用,如下所示:

aggregate([
{ $match: {"username": "foouser"}},
{ $group: {
  ...other items..
  "last_active": max(updated) OR IF EMPTY max(uploaded)
}
]);

我想将 "last_active" 设置为更新的最大时间戳,以便获取用户对其所有项目的最后一次活动。但不是每个项目都有更新-属性。也许在用户的任何元素中都有 on update-属性 。所以如果 max(updated) 是空的,他应该选择 max(uploaded).

任何人都可以在团购中帮我解决这个问题吗?

聚合流水线版本变化较大,建议使用mongodb最新稳定版。

尝试组合 $max 和 $setUnion 运算符,如下所示:

db.Collection.aggregate([
    { $match: {"username": "foouser"}},
    { $group: {
    ...other items..
    "last_active": { $max: { $setUnion: [ "$updated", "$uploaded" ] } }
    }
]);

或者 $ifNull 和 $max:

db.Collection.aggregate([
    { $match: {"username": "foouser"}},
    { $group: {
    ...other items..
    "last_active": { $max: { $ifNull: [ "$updated", "$uploaded" ] } }
    }
]);