python Store text file in mangodb

Peter Otten __peter__ at web.de
Mon Jun 13 04:26:15 EDT 2022


On 12/06/2022 14:40, Ayesha Tassaduq wrote:
> Hi i am trying to store a text file into MongoDB but i got the error .
> "failing because no such method exists." % self.__name.split(".")[-1]
> TypeError: 'Collection' object is not callable. If you meant to call the 'insert' method on a 'Collection' object it is failing because no such method exists.
>
> Can anyone please tell what is wrong here
> i also tried to do it with insert_one  and insert_many
> but when i try to do it with insert_many it shows error
>    raise TypeError("documents must be a non-empty list")
> TypeError: documents must be a non-empty list

Read the error messages carefully:

(1) "...If you meant to call the 'insert' method on a 'Collection'
object it is failing because no such method exists."

It may be a bit unfortunate that attributes spring into existence when
you try to access them, but you want an  "insert" method, and the error
message warns you that no such method exists. You can run your script in
idle and then type

 >>> collections.insert

to see what it actually is.

(2) "...documents must be a non-empty list"

The insert_many() method expects a non-empty list of documents Example:

collection.insert_many([text_file_doc])

You don't provide an error message for insert_one(), and indeed it
should work where you tried insert():

collection.insert(text_file_doc)


> from pymongo import MongoClient
> client = MongoClient()
> db = client.test_database  # use a database called "test_database"
> collection = db.files   # and inside that DB, a collection called "files"
>
> f = open('hashes.txt')  # open a file
>
> # build a document to be inserted
> text_file_doc = {"file_name": "hashes.txt"}
> # insert the contents into the "file" collection
> collection.insert(text_file_doc)
>
> File names Hshes.txt has follown=ing data

You are not yet at the point where you are using the file or its
contents, so the file object and the file's contents could be omitted.
Generally it is a good idea

- to make your script as short as possible as long as it still produces
the error. In the process you will often be able to fix the problem
yourself.

- always provide the tracebacks using cut-and-paste. That is often
sufficient to diagnose and fix the problem.

> Hash 1: 39331a6a2ea1cf31a5014b2a7c9e8dfad82df0b0666e81ce04cf8173cc5aed
>
> Hash 2: 0e0ff63b7e5e872b9ea2f0d604b5d5afd6ba05665e52246fa321ead5b79c00ad
>
> Hash 3: 89241ce841704508be1d0b76c478c9575ec8a7ec8be46742fd5acb0dc72787f3
>
> Hash 4: 80283cb08f91b415aae04bcada0da1ca3e37bbe971ae821116b4d29008970bdb



More information about the Python-list mailing list