inserting items in list in mongodb document

2019-07-17 04:44发布

问题:

I have a document like this

{ "_id" : "decfed9a04b997d", "pushed_list" : [ ] }

and I want to update/insert "pushed_list" by these sub items stored in a python list

lis1 = 
    [
       {
        item : 'item1',
        desc : 'desc_item1'
       },
       {
        item : 'item2',
        desc : 'desc_item2'
       },
       { ........................
       }

    ]

I tried this

db.monitor.update({'_id' : 'dbjkdd'}, { '$push':{'pushed_list': {'$each':{lis1}}}})

Its giving me an error.

Traceback (most recent call last):
  File "monitor.py", line 13, in <module>
    db.monitor.update({'_id' : 'dbjfdd'}, { '$push':{'pushed_list': {'$each':{lis1}}}})
TypeError: unhashable type: 'list'

回答1:

I found the answer, pretty foolish on my side; just have to remove extra braces {}

Instead of this

db.monitor.update({'_id' : 'dbjkdd'}, { '$push':{'pushed_list': {'$each':{lis1}}}})

Use this

db.monitor.update({'_id' : 'dbjkdd'}, { '$push':{'pushed_list': {'$each':lis1}}})

i.e remove '{'after '$each' and its corresponding '}'