client = MongoClient("mongodb+srv://<username>:<password>@smartcontainer-jp0au.mongodb.net/test?retryWrites=true&w=majority")
db = client.get_database('SmartContainerDemo')
collection = db.get_collection(u'devices')
def update_device(device_num, readingGram, lastRead):
doc_ref = db.collection(u'devices').document(u'device' + str(device_num))
doc_ref.set({u'readingGram': readingGram, u'lastRead': lastRead})
Can someone please let me know what the issue is and how I would go about fixing this? (I do have the correct password and username in for the client)
client = MongoClient("mongodb+srv://<username>:<password>@smartcontainer-jp0au.mongodb.net/test?retryWrites=true&w=majority")
db = client['SmartContainerDemo']
collection = db[u'devices']
def update_device(device_num, readingGram, lastRead):
doc_ref = db.collection(u'devices').document(u'device' + str(device_num))
doc_ref.set({u'readingGram': readingGram, u'lastRead': lastRead})
Hi,
The error basically described what’s wrong with the code. In Pymongo, the method collection
doesn’t exist on a Database
object. I’m not sure where you get the example code from, but db.collection(...)
is not valid in Pymongo. Neither is collection(...).document(...)
, as document()
is not a valid method of the Collection
object.
Without more information about your data and the operation you’re trying to do, you might be able to modify your update_device()
similar to:
client = pymongo.MongoClient('mongodb://localhost:27017')
db = client.test
coll = db.test
def update_device(device_num, readingGram, lastRead):
return coll.update_one({'device': device_num}, {'$set': {'readingGram': readingGram, 'lastRead': lastRead}})
print(update_doc(0, 100, 123))
Assuming this is the document you’re trying to update:
> db.test.find()
{
"_id": 0,
"device": 0,
"readingGram": 0,
"lastRead": 0
}
Running the above Python code would result in the document to be updated to:
> db.test.find()
{
"_id": 0,
"device": 0,
"readingGram": 100,
"lastRead": 123
}
Note that in the example above I’m just guessing on your schema and the code might not work as intended if run on your actual data. If you could post the example document and the operation you needed to do, if you need more help with this.
Best regards,
Kevin