简体   繁体   中英

MongoDB update array of object in python

I am trying to update mongodb with array of object, But receiving error. Here is my code

class DocDetails:
    def __init__(self, _name, _createDate, _updateDate):
        self.name = _name
        self.createDate = _createDate
        self.updateDate = _updateDate

aa = DocDetails("Doc1","01-01-2018","05-01-2018")
bb = DocDetails("Doc2","09-12-2019","20-12-2019")

testArray = []
testArray.append(aa)
testArray.append(bb)
print(testArray[1].name)  #Print Doc2, which is right

targetCollectionName.update(
            {'_id':item['_id']},

            { '$push':{'DocumentDetails': {'$each': testArray}}

             },
            upsert=False
        )

Now I am getting encoding error

bson.errors.InvalidDocument: cannot encode object: <__main__.DocDetails object at 0x03F14410>, of type: <class '__main__.DocDetails'>

How to handle this?

You can use the built-in __dict__ attribute to convert your object into a dictionary that pymongo will be happy with:

from pymongo import MongoClient
from bson.json_util import dumps

db = MongoClient()['mydatabase']

class DocDetails:
    def __init__(self, _name, _createDate, _updateDate):
        self.name = _name
        self.createDate = _createDate
        self.updateDate = _updateDate

aa = DocDetails("Doc1","01-01-2018","05-01-2018")
db.mycollection.insert_one(aa.__dict__)

print(dumps(db.mycollection.find_one({}, {'_id': 0}), indent=4))

gives:

{
    "name": "Doc1",
    "createDate": "01-01-2018",
    "updateDate": "05-01-2018"
}

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