Importing a plain text file into MongoDB

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:

How to do 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 ...

Get Python Business Intelligence Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.