如何根据条件更新具有 2 个可能值的字段? [英] how can I update a field with 2 possible values according to a condition?

查看:52
本文介绍了如何根据条件更新具有 2 个可能值的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 mongodb 的新手.

I am new to mongodb.

我有一个这样的数据库:

I have a database like this:

{
 "universe": "DC",
 "characters": [
 {"name": "superman", "selected": true}, 
 {"name": "wonder woman", "selected": false}, 
 {"name": "flash", "selected": false}
},
{ 
 "universe": "marvel",
 "characters": [
  {"name": "wolverine", "selected": false}, 
  {"name": "cyclops", "selected": false}
}

如果universe 是DC",我正在尝试更新它的characters,其中角色的name 等于wonder"女人",然后我希望所属的 selected 字段更新为 true 并且在同一个文档中,与 name 不匹配的字符《神奇女侠》在选择

I'm trying to make if the universe is "DC", update its characters where the character's name equals "wonder woman", then I want the belonging selected field to be updated to true and in this same document, characters that do not match the name of "wonder woman" have the value of false in selected

mydb.collection.findOneAndUpdate(
{
  "universe": "DC", //only DC universe
  "characters.name":"wonder woman"   
},
{
  $set: {
    "characters.$.selected": true,  // I dont know how to set false to other objects where name!=wonder woman
  },
})

想要的结果:

 {"name": "superman", "selected": false}, 
 {"name": "wonder woman", "selected": true}, 
 {"name": "flash", "selected": false}

我该怎么做?

推荐答案

从 MongoDB 3.6 开始,更新数组字段时,可以指定 arrayFilters 确定要更新哪些数组元素.

Starting in MongoDB 3.6, when updating an array field, you can specify arrayFilters that determine which array elements to update.

mydb.collection.findOneAndUpdate(
    {
        universe: "DC"
    },
    {
        $set : {
            "characters.$[has].selected" : true,
            "characters.$[not].selected" : false
        }
    },
    { 
        arrayFilters: [ 
            { 
                "has.name": { $eq: "wonder woman" }
            },
            { 
                "not.name": { $ne: "wonder woman" }
            } 
        ],
        returnNewDocument: true
    }
)

  • 以下操作查找universe字段等于DC"的文档
  • 使用过滤位置运算符 $[]arrayFiltersselected 修改为 true 用于 characters 数组中的所有元素,其中 name (has.name)$eq 到 ";神奇女侠"
  • 另一边的arrayFilterscharacters数组中所有元素的selected修改为falsename (not.name)$ne 到神奇女侠".
  • returnNewDocument: true 返回更新的文档
    • The following operation finds a document where the universe field equals "DC"
    • uses the filtered positional operator $[<identifier>] with the arrayFilters to modify the selected to true for all elements in the characters array where the name (has.name) is $eq to "wonder women"
    • other side the arrayFilters to modify the selected to false for all elements in the characters array where the name (not.name) is $ne to "wonder women".
    • returnNewDocument: true return updated document
    • 这篇关于如何根据条件更新具有 2 个可能值的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆