Dev
Dev

Reputation: 423

mongodb element match and update query

I have a collection named users details below

[{
"userId": "00UPQAARGT7",
"userPreferences": [{
    "pId": "59SDS64675A00096D48CB",
    "pData": [{
            "name": "FORMAT",
            "value": "CSV"
        },
        {
            "name": "LAN",
            "value": "E"
        }
    ]
},
{
    "pId": "59SDS64675A00096D59DB",
    "pData": [{
            "name": "FORMAT",
            "value": "DOC"
        },
        {
            "name": "LAN",
            "value": "N"
        }
    ]
}
]},
{
"userId": "02UPQAARST7",
"userPreferences": [
{
    "pId": "59SDS64675A00096D48DB",
    "pData": [{
            "name": "FORMAT",
            "value": "CSV"
        },
        {
            "name": "LAN",
            "value": "N"
        }
    ]
},
{
    "pId": "59SDS64675A00096D59DB",
    "pData": [{
            "name": "FORMAT",
            "value": "PPT"
        },
        {
            "name": "LAN",
            "value": "N"
        }
    ]
}
]}  
]

I want to set userPreferences.pData.value to "TAB" where userPreferences.pData.name is "FORMAT" and userPreferences.pData.value to "FRN" where userPreferences.pData.name is "LAN" but want to apply condition where userId in ["00UPQAARGT7", "02UPQAARST7"] and userPreferences.pId in ["59SDS64675A00096D48CB","59SDS64675A00096D59DB"]

any help how to do in mongodb with single query

I'm using mongodb 3.4.1 version

Upvotes: 0

Views: 514

Answers (1)

dnickless
dnickless

Reputation: 10918

You cannot do this the way you want to for two reasons:

  1. In MongoDB 3.4 the positional operator '$' only matches the first found subdocument. This has been changed in v3.6 where you can now use the $[] syntax to target all matching subdocuments.
  2. You cannot specify a conditional update in any version of MongoDB as of today. There is an open feature request for this, though: https://jira.mongodb.org/browse/SERVER-6566

So you are basically left with the good old (unfortunately slower) alternative of doing the changes on the client side which you can find loads of examples for, e.g. here:

MongoDB update multiple subdocuments with or query

Update all sub-documents inside document mongodb

Upvotes: 1

Related Questions