【问题标题】:MongoDB to return formatted object when no results can be foundMongoDB在找不到结果时返回格式化对象
【发布时间】:2020-03-05 19:27:34
【问题描述】:

我的MongoDB 聚合管道中有以下阶段,它返回销售的数量和总和,效果很好:

{
  $lookup: {
    from: 'sales',
    let: { part: '$_id' },
    pipeline: [
        { $match: { $and: [{ $expr: { $eq: ['$partner', '$$part'] } }] } },
        { $group: { _id: null, qty: { $sum: 1 }, soldFor: { $sum: '$soldFor' } } },
        { $project: { _id: 0, qty: 1, soldFor: 1 } }],
    as: 'sales'}},
    { $unwind: { path: '$sales', preserveNullAndEmptyArrays: true } },
    { $project: { _id: 1, sales: 1 }
}

但是,如果没有销售,那么 $project 投影会返回一个空的销售对象,但我真正想要的是它返回一个完整的对象,但带有 0 - 像这样:

{
  sales: {
    qty: 0,
    soldFor: 0
  }
}

【问题讨论】:

标签: mongodb pipeline aggregation


【解决方案1】:

您可以在此处使用$cond 运算符

{
  "$project": {
    "_id": 1,
    "sales": {
      "$cond": [
        { "$eq": [{ "$size": "$sales" }, 0] },
        {
          "sales": {
            "qty": 0,
            "soldFor": 0
          }
        },
        "$sales"
      ]
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多