【问题标题】:Update array elements by index if they don't contain some key如果数组元素不包含某些键,则按索引更新数组元素
【发布时间】:2022-04-10 00:25:56
【问题描述】:

我正在尝试更新特定文档中数组中的多个元素,其中我有需要更新的元素的索引,但前提是某些键不存在。

MongoDB Playground Link

假设我有一个文件:

{
    "key": 1,
    "questions": [
      {
        "text": "first",
      },
      {
        "text": "second",
      },
      {
        "text": "third",
        "answered": "balloon",
      },
    ],
},

我想用一个新的“已回答”字段更新第 2 项和第 3 项(索引 2 和 3),但只更新那些还没有“已回答”字段的项。 这是我目前管理的查询:

db.collection.update({
  "key": 1,
},
{
  $set: {
    "questions.1.answered": "second answer",
    "questions.2.answered": "third answer",
  }
}
)

这将更新第二个和第三个索引,并将它们都设置为“已回答”。但我想跳过“第 3 个”,因为它已经有了“已回答”的键。 我怎样才能实现这种排除? 也许在 ArrayFilters 行中有什么?


预期输出:

{
    "key": 1,
    "questions": [
      {
        "text": "first",
      },
      {
        "text": "second",
        "answered": "second answer", //Added field
      },
      {
        "text": "third",
        "answered": "balloon", //Should not update as it already had "answered"
      },
    ],
},

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    您想要可选的更新,所以我使用了管道更新。
    也许你可以只使用更新操作符来做到这一点,但波纹管也可以。

    查询

    • 在“数据”上放置答案数组和相应的索引
    • 问题索引图(0 1 2 ...)
    • 检查索引是否在需要更改的索引中
    • 如果他们没有答案,得到答案

    PlayMongo

    update({"key" : 1},
    [{"$set": 
        {"data": {"answers": ["index1-a", "index2-a"], "indexes": [1, 2]}}},
      {"$set": 
        {"questions": 
          {"$map": 
            {"input": {"$range": [0, {"$size": "$questions"}]},
              "in": 
              {"$let": 
                {"vars": {"question": {"$arrayElemAt": ["$questions", "$$this"]}},
                  "in": 
                  {"$cond": 
                    [{"$and": 
                        [{"$in": ["$$this", "$data.indexes"]},
                          {"$eq": [{"$type": "$$question.answered"}, "missing"]}]},
                      {"$mergeObjects": 
                        ["$$question",
                          {"answered": 
                            {"$arrayElemAt": 
                              ["$data.answers",
                                {"$indexOfArray": ["$data.indexes", "$$this"]}]}}]},
                      {"$arrayElemAt": ["$questions", "$$this"]}]}}}}}}},
      {"$unset": ["data"]}])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2021-08-13
      • 2018-07-17
      • 2017-01-07
      相关资源
      最近更新 更多