简体   繁体   中英

Adding value to array in sub-document (nested within main doc) without duplication - MongoDB

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, ie UpSert
  3. The command be the same for both action (ie 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']}
   ]
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM