how can I update a field with 2 possible values according to a condition?

前端 未结 1 1248
心在旅途
心在旅途 2021-01-26 22:57

I am new to mongodb.

I have a database like this:

{
 "universe": "DC",
 "characters": [
 {"name": "superman&qu         


        
1条回答
  •  有刺的猬
    2021-01-26 23:29

    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
        }
    )
    
    • The following operation finds a document where the universe field equals "DC"
    • uses the filtered positional operator $[] 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

    0 讨论(0)
提交回复
热议问题