1

it is quite complicated with the nested documents, but please let me know if you all has any solutions, thanks.

To summarize, I would like to:

  1. Add a value to an array (without duplication), and the array is within a sub-document, that is within an array of a main document. (Document > Array > Subdoc > Array)
  2. The subdocument itself might not exist, so if not exist, the subdocument itself need to be added, i.e. UpSert
  3. The command be the same for both action (i.e. adding of value to subdoc's array, and adding of subdoc)

I have tried the following, but it doesn't work:

key = {'username':'user1'}

update1 = {
'$addToSet':{'clients':{
 '$set':{'fname':'Jessica'},
 '$set':{'lname':'Royce'},
 '$addToSet':{'cars':'Toyota'}
  }
 }
}
#the document with 'Jessica' and 'Royce' does not exist in clients array, so a new document should be created
update2 = {
'$addToSet':{'clients':{
 '$set':{'fname':'Jessica'},
 '$set':{'lname':'Royce'},
 '$addToSet':{'cars':'Honda'}
  }
 }
}
#now that the document with 'Jessica' and 'Royce' already exist in clients array, only the value of 'Honda' should be added to the cars array

mongo_collection.update(key, update1 , upsert=True)
mongo_collection.update(key, update2 , upsert=True)

error message: $set is not valid for storage

My intended outcome:

Before:

{
   'username':'user1',
   'clients':[
   {'fname':'John',
    'lname':'Baker',
    'cars':['Merc','Ferrari']}
   ]
}

1st After:

{
   'username':'user1',
   'clients':[
   {'fname':'John',
    'lname':'Baker',
    'cars':['Merc','Ferrari']},
   {'fname':'Jessica',
    'lname':'Royce',
    'cars':['Toyota']}
   ]
}

2nd After:

{
   'username':'user1',
   'clients':[
   {'fname':'John',
    'lname':'Baker',
    'cars':['Merc','Ferrari']},
   {'fname':'Jessica',
    'lname':'Royce',
    'cars':['Toyota','Honda']}
   ]
}

1 Answer 1

1

My understanding says you won't be able to completely achieve intended solution directly. You can very well do nested update or upsert but duplication check probably not, as there is no direct way to check item contains in a array document.

For upsert operation you can refer mongodb update operation doc or bulk operation. And for duplication probably you need to have separate logic to identify.

Sign up to request clarification or add additional context in comments.

1 Comment

I see... then it would be quite a complicated tasks to first check if the array contains the document, then if not, add the document, if yes, i'll need to check again if the array within the subdoc has the value. Not sure if anyone else have come across this problem, and have a more efficient way of handling this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.