通过findOneAndUpdate查询使用对象数组的总和更新根

通过findOneAndUpdate查询使用对象数组的总和更新根

本文介绍了猫鼬:通过findOneAndUpdate查询使用对象数组的总和更新根数据属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Node mongoose lib更新mongo集合中的数组元素之一.这是我的mongo模式的样子:

I'm trying to update one of the array elements in a mongo collection using the Node mongoose lib. Here is how my mongo schema looks like:

{
    "_id": ObjectId("5f8a94ccc8452643f1498419"),
    "private": false,
    "score": 2000,
    "questions": [{
        "_id": ObjectId("5f8a94e8c8452643f149841c"),
        "order": 1,
        "category": "TEXT",
        "definition": "about us",
        "score": 1,
    }, {
        "_id": ObjectId("5f8a94e8c8452643f149841d"),
        "order": 2,
        "category": "HTML",
        "definition": "about us",
        "score": 0.5
    }]
}

我正在更新问题数组中的分数,要更新的根数组处的score属性是数组分数的总和,即

I'm updating the score inside the question array, the score attribute at the root array to be updated which is the sum of the array score i.e.

root score => question array1.score + array2.score

我在猫鼬功能下面使用了

I used below mongoose function:

  Model.findOneAndUpdate(
    {
      _id: id,
      "questions._id": qid,
    },
    {
     '$set': {
          'questions.$.order': 1,
          'questions.$.score': 1,
          'questions.$.type': 'HTML',
          '$sum': { 'score': 'questions.score' }
      }
    })

虽然所有其他属性都已更新,但根分数从未更新.

While all other attributes are getting updated, the root score is never getting updated.

使用单个查询可以完全执行两次更新吗?

Is this at all possible to perform both of this updates using a single query?

推荐答案

您可以使用使用聚合管道更新,从MongoDB 4.2开始,

You can use update with aggregation pipeline starting from MongoDB 4.2,

  • $set更新ID与qid
  • 匹配的匹配问题
  • $setquestions数组的分数更新根分数
  • $set to update matching question that id matches with qid
  • $set to update root score from score of questions array
let id = mongoose.Types.ObjectId("5f8a94ccc8452643f1498419");
let qid = mongoose.Types.ObjectId("5f8a94e8c8452643f149841c");
let question = {
  score: 1,
  order: 1,
  category: "TEXT"
};

Model.findOneAndUpdate(
  { _id: id },
  [{
    $set: {
      questions: {
        $map: {
          input: "$questions",
          in: {
            $mergeObjects: [
              "$$this",
              {
                $cond: [
                  { $eq: ["$$this._id", qid] },
                  question, // add update fields in object
                  {}
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      score: {
        $reduce: {
          input: "$questions",
          initialValue: 0,
          in: { $add: ["$$value", "$$this.score"] }
        }
      }
    }
  }]
)

游乐场

这篇关于猫鼬:通过findOneAndUpdate查询使用对象数组的总和更新根数据属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 04:23