Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何基于mongodb聚合中数组内的另一个字段有条件地将值设置为父字段?_Mongodb_Mongoose_Mongodb Query_Aggregation Framework - Fatal编程技术网

如何基于mongodb聚合中数组内的另一个字段有条件地将值设置为父字段?

如何基于mongodb聚合中数组内的另一个字段有条件地将值设置为父字段?,mongodb,mongoose,mongodb-query,aggregation-framework,Mongodb,Mongoose,Mongodb Query,Aggregation Framework,我想从聚合映射操作符内部在函数级别设置一个变量。这是我到目前为止所拥有的一个片段 $project: { collectionId: 1, name: 1, description: 1, image: 1, created: 1, updated: 1, isPresent: "no", "products": { $map: { "input": "$products", as: "product", in: {

我想从聚合映射操作符内部在函数级别设置一个变量。这是我到目前为止所拥有的一个片段

$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",
}

我想根据条件在中的map操作符中将isPresent节点值设置为yes。目前,我一直把它保持在“是”。但这不起作用

操作方法是什么?

您可以使用和运算符:

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

注意:

当我们使用
$in
时,每个文档都必须有
产品
数组,否则
$in
将出错,如果存在任何此类情况,您需要为没有
产品
数组的文档设置跳过条件。

您可以使用和运算符:

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

注意:


当我们使用
$in
时,每个文档都必须有
产品
数组,否则
$in
将出错,如果存在任何此类情况,您需要为那些没有
产品
阵列的文档设置跳过的条件。

您希望在
产品
阵列上检查的条件是什么?也许更好地解释一下什么情况下产品使父字段
isPresent:“Yes”
我有一个名为productId的局部变量。。。我正在检查productId是否等于products数组中的任何productId。既有
isPresent
又有
$isPresent
,您指的是哪一个?您想检查
products
数组的条件是什么?也许更好地解释一下什么情况下产品使父字段
isPresent:“Yes”
我有一个名为productId的局部变量。。。我正在检查productId是否等于products数组中的任何productId。有
isPresent
$isPresent
,您指的是哪一个?