The ease of MongoDB combined with the power of GraphQL: I cannot think of a better combination than this! I will be curating a series of articles for working on GraphQL + MongoDB + Django. This is the first part of that series.
In this article, you will learn how to-
- import data into MongoDB using a CSV file
- install GraphQL and other related Django libraries
- pull data from MongoDB to Django
From .csv to MongoDB Collection
Run this code directly in your terminal (not mongod console) to import a CSV file from your local. We are using mongoimport which is a tool/command that enables us to import any JSON, CSV to TSV file.
mongoimport -d vendors -c vendors --type csv --file vendorlist.csv --headerline
-d: database name
-c: collection name
-headerline: used to keep the headers
Installing GraphQL in Django
Yet another saga of versioning mismatch. I have already played with them so you don't have to 🙂
Below are the errors that were causing a lot of confusion regarding the versions-
Error when the version of graphene-django was 3.0b7 which was latest but it couldn’t import the get_default_backend package
Commands to install each library/package/driver
pip install graphene==2.1.8
python -m pip install graphql-core==2.3.2
python3 -m pip install pymongo==3.12.1
pip install "graphene-django>=2.0"
💡 Don’t forget to add ‘graphene-django’ and ‘graphene’ to your settings.py file
Getting a MongoDB collection’s data to Django project
Import the Document class from mongoengine library and subsequently import the fields that are required.
💡 Your can check the datatype of the field in MongoDB in MongoDB Atlas console and then import the field in your Django project. Example- The ID field in a document id always an ObjectIDField.
I have a MongoDB document vendors and the class that is accessing the document is VendorData.
This was the first part of the series of MongoDB+Django+GraphQL tutorials. I will explain more about writing queries in Django and GraphQL in the later parts.
Top comments (0)