With the information you provided it is practically impossible to answer you. I explain:
1) You have not given any background information (you will include a document in the collection
and want to know if the document was correctly inserted? Or another user will add a document and you want to send a notification to it? Among other several options...)
2) In your question you quote collection
, but in your example you use the database
. You want to know if a document has been inserted into collection
or in the database
as a whole?
If you are entering and want to check that the operation was successful, consider checking acknowledged
and if you can access the new document id.
>>> new_document = collection.insert_one({'teste0': 'teste0'})
>>> new_document.acknowledged
True
>>> print(new_document.inserted_id)
5d8df5f3d6866c94867acc3b
According to the official documentation, acknowledged == False
indicates that all other attributes of the class will be InvalidOperation
when accessed.
Of course you can also use the same logic when inserting more than one document in the same operation:
>>> new_documents = collection.insert_many([{'teste1': 'teste1'}, {'teste2': 'teste2'}])
>>> new_documents.acknowledged
True
>>> for id in new_documents.inserted_ids:
... print(id)
...
5d8df7a3d6866c94867acc3c
5d8df7a3d6866c94867acc3d
In fact, you can even try to predict other errors when performing an operation. A very generic approach is the following:
try:
#Qualquer uma de suas operações
except pymongo.errors.PyMongoError as erro:
logging.error(f'Erro inesperado com o Mongo: {erro.__class__};\n{erro}')
#Código para tratar alguma exceção genérica
pymongo.errors.PyMongoError
is base class for all pymongo exceptions.
If you don’t have direct access to the operation, consider using count_documents
:
>>> num_docs = collection.count_documents({})
#Como não passamos nenhum filtro, checamos todos os documentos da collection
>>> num_docs
7
...
...
...
...
'''
Checando se um novo documento foi inserido
'''
>>> new_num_docs = collection.count_documents({})
>>> if new_num_docs > num_docs: #Novo documento inserido!
... print('Um novo documento foi adicionado.')
... print(new_num_docs, num_docs)
...
Um novo documento foi adicionado.
8 7
pq Voce does not add a function to your backend, by adding Collection sends a notification something like this
– rafaelphp