$addToSet

https://www.mongodb.com/docs/manual/reference/operator/update/addToSet/

  1. [
  2. {
  3. "name": "s1",
  4. "skills": ["python", "shell"]
  5. },
  6. {
  7. "name": "s2",
  8. "skills": ["perl", "r"]
  9. }
  10. ]
  1. # 更新单个元素到列表,自动去重
  2. _update = {
  3. '$addToSet': [
  4. 'skills': 'perl'
  5. ]
  6. }
  7. col.update({'name': 's1'}, _update) # skills: ['python', 'shell', 'perl']
  8. # 更新列表素到列表,自动去重
  9. _update = {
  10. '$addToSet': [
  11. 'skills': {'$each': ['perl', 'r']}
  12. ]
  13. }
  14. col.update({'name': 's1'}, _update) # skills: ['python', 'shell', 'perl', 'r']