Update on Mongodb

Asked

Viewed 45 times

-2

Is there a function that allows you to send a message when some data is added to Collection?

Kind of a logs

For example:



data = {
    "_id": 12345678910
}

return db.insert_one(data)

Terminal:

Um novo documento foi adicionado na collection!: "_id": 12345678910


  • pq Voce does not add a function to your backend, by adding Collection sends a notification something like this

1 answer

0

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
  • I wanted to make every document added to Collection(db) be printed something in the terminal

  • I put a better example

  • How, where and by whom documents will be added?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.