0

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

mickl
  • 48,568
  • 9
  • 60
  • 89
Dev
  • 413
  • 10
  • 27
  • 3
    I'd suggest you try re-frame your question first. I have a headache after reading it and I didn't even make it to the end. – sharkdawg Feb 28 '18 at 17:22
  • have you tried https://docs.mongodb.com/manual/reference/method/db.collection.update/ at all? – Alex Blex Feb 28 '18 at 17:22

1 Answers1

1

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

dnickless
  • 10,733
  • 1
  • 19
  • 34