使用MongoDB的$$]运算符遍历两个数组并更新相关文档

时间:2018-11-09 17:28:59

标签: mongodb aggregation-framework

升级到Mongo 4.0后,我尝试使用Mongo的新$[]功能。我基本上想做的是获取一个或多个“覆盖” ID并遍历两个数组,以使更新根据与“覆盖” ID中传递的匹配进行过滤。我的代码的相关部分如下所示:

if (coverage) {
    let arrCoverage = [];
    arrCoverage = coverage.split(",");

    if (arrCoverage) {
      // convert each ID to a mongo ID
      let mongoArrCoverage = arrCoverage.map(coverage => new mongo.ObjectID(coverage));

      if (mongoArrCoverage) {
        try {
          let bulk = db.collection("customers").initializeUnorderedBulkOp();
          let count = 0;
          let batch = 1;

          db.collection("customers")
            .aggregate([
              {
                $match: {
                  "paymentOptions.coverages._id": {
                    $in: mongoArrCoverage
                  }
                }
              },
              {
                $unwind: "$paymentOptions"
              },
              {
                $unwind: "$coverages"
              },
              {
                $match: {
                  "coverages._id": {
                    $in: mongoArrCoverage
                  }
                }
              },
              {
                $project: {
                  _id: 0,
                  coverages_id: "$coverages._id",
                  "coverages.status": "$coverages.status"
                }
              }
            ])
            .forEach(function(doc) {
              let coverages_id = doc.paymentOptions.coverages_id;
              bulk
                .find({
                  "paymentOptions.coverages._id": coverages_id
                })
                .updateOne({
                  $set: {
                    "paymentOptions.$[].coverages.$[].coverageEnd": lastDayOfMonth,
                    "paymentOptions.$[].coverages.$[].status": doc.paymentOptions.coverages.status == "active" ? null : doc.paymentOptions.coverages.status,
                    "paymentOptions.$[].coverages.$[].lastAdvanceDate": today
                  }
                });
              count++;
              if (count == batch) {
                bulk.execute();
                bulk = db.collection("customers").initializeUnorderedBulkOp();
                count = 0;
              }
            });

          if (count > 0) {
            bulk.execute();
          }

          res.sendStatus(200);
        } catch (e) {
          console.log(e);
        }
      }
    }
  }
};

但这似乎并没有达到预期的更新。我认为问题可能出在最初的汇总中吗?此代码看起来正确吗?在我们以前的模型中,“ coverage”数组位于文档的根目录。现在,它是“ paymentOptions”中的一个属性,它也是一个数组,我假设我在初始聚合时必须$unwind这两个数组。

顺便说一下,文档的相关部分如下所示:

{
  _id: <ObjectId>,
  someProp: <value>,
  paymentOptions: [
    {
     _id: <ObjectId>,
     otherProp: <value>,
     coverages: [
        {
          _id: <ObjectId>,  // Want to match on this
          coverageStart: <Date>,
          coverageEnd: <Date>, // Want to update this
          status: "active"
        },
        {
          _id: <ObjectId>, // Want to match on this
          coverageStart: <Date>,
          coverageEnd: <Date>, // Want to update this
          status: "active"
        }
     ]
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

您必须使用数组过滤器。另外,要展开嵌套数组,还必须使用点表示法来包括整个路径。

类似的东西应该起作用

if (coverage) {
  let arrCoverage = [];
  arrCoverage = coverage.split(",");
  if (arrCoverage) {
    // convert each ID to a mongo ID
    let mongoArrCoverage = arrCoverage.map(coverage => new mongo.ObjectID(coverage));
    if (mongoArrCoverage) {
      try {
        let bulk = db.collection("customers").initializeUnorderedBulkOp();
        let count = 0;
        let batch = 1;
        db.collection("customers").aggregate([{
          $match: {
            "paymentOptions.coverages._id": {
              $in: mongoArrCoverage
            }
          }
        }, {
          $unwind: "$paymentOptions"
        }, {
          $unwind: "$paymentOptions.coverages"
        }, {
          $match: {
            "paymentOptions.coverages._id": {
              $in: mongoArrCoverage
            }
          }
        }, {
          $project: {
            _id: 0,
            "paymentOptions_id": "$paymentOptions._id",
            "coverages_id": "$paymentOptions.coverages._id",
            "coverages_status": "$paymentOptions.coverages.status"
          }
        }]).forEach(function(doc) {
            let paymentOption_id = doc.paymentOptions_id;
            let coverages_id = doc.coverages_id;
            let status = doc.coverages_status;
            bulk.find({}).arrayFilters([
                {"po._id": paymentOption_id},
                {"cr._id":  coverages_id}]).updateOne({
                $set: {
                  "paymentOptions.$[po].coverages.$[cr].coverageEnd": lastDayOfMonth,
                  "paymentOptions.$[po].coverages.$[cr].status": status == "active" ? null : status,
                  "paymentOptions.$[po].coverages.$[cr].lastAdvanceDate": today
                }
              }); count++;
              if (count == batch) {
                bulk.execute();
                bulk = db.collection("customers").initializeUnorderedBulkOp();
                count = 0;
              }
            });
          if (count > 0) {
            bulk.execute();
          }
          res.sendStatus(200);
        }
        catch (e) {
          console.log(e);
        }
      }
    }
  }
};