December 2015
Beginner to intermediate
202 pages
4h
English
Let us say that you have a text file that you need to import into MongoDB so you can make it searchable. This file is not comma or tab separated; it just has a lot of text which you want to keep. Use the following recipe to import it:
from pymongo import MongoClient
client = MongoClient()
db = client.pythonbicookbook
files = db.files
f = open('name_of_file_here.txt')
text = f.read()
doc = {
"file_name": "name_of_file_here.txt",
"contents" : text }
files.insert(doc)The first thing we do is import PyMongo and create a connection to the database. We then tell PyMongo the name of the collection that we want to use; in this instance, the files collection. Next we use the built-in file handling functionality ...
Read now
Unlock full access