【问题标题】:How to conditionally set a value to parent field based on another field inside an array in mongodb aggregate?如何根据mongodb聚合中数组内的另一个字段有条件地将值设置为父字段?
【发布时间】:2020-06-20 03:20:28
【问题描述】:

我想从聚合映射运算符内部在函数级别设置一个变量。这是我到目前为止所拥有的sn-p。

$project: {
  collectionId: 1,
  name: 1,
  description: 1,
  image: 1,
  created: 1,
  updated: 1,
  isPresent: "no",
  "products": {
    $map: {
      "input": "$products",
      as: "product",
      in: {
        "title": "$$product.name",
        "imageUrl": "$$product.mainImage",
        "productId": "$$product.productId",
        "$isPresent": "yes"
      }
    }
  },
  total: {
    $size: "$products"
  },
  userId: "$user.userId",
  userName: "$user.name",
}

我想根据条件在地图运算符中将 isPresent 节点值设置为是。暂时我一直保持“是”。但这不起作用。

有什么办法呢?

【问题讨论】:

  • 您想在products array 上检查的条件是什么?也许更好地解释一下产品的哪些案例是父字段isPresent : 'Yes'
  • 我有一个名为 productId 的局部变量...我正在检查 productId 是否等于 products 数组中的任何 productId。
  • isPresent$isPresent 都有,你指的是哪一个?

标签: mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

您可以使用$in$cond 运算符:

db.collection.aggregate([
    /** `$products.productId` gives an array of 'productId''s from products array */
    {
      $addFields: { isPresent: { $cond: [ { $in: [ 2, "$products.productId" ] }, "Yes", "No" ] } }
    }
  ])

测试: mongoplayground

注意:

当我们使用$in 时,每个文档都必须有products 数组,否则$in 将出错,如果有任何此类情况,您需要条件跳过那些文档没有products 数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-11
    • 2015-04-23
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2019-03-25
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多