DEV Community

Cover image for Querying Data from MongoDB using GraphQL in Django: Get-Go (1)
shlokabhalgat
shlokabhalgat

Posted on

Querying Data from MongoDB using GraphQL in Django: Get-Go (1)

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
Enter fullscreen mode Exit fullscreen mode

where

-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 🙂

Version table

Below are the errors that were causing a lot of confusion regarding the versions-

Error in terminal

Error when the version of graphene-django was 3.0b7 which was latest but it couldn’t import the get_default_backend package

library name

Commands to install each library/package/driver

  • graphene
pip install graphene==2.1.8
Enter fullscreen mode Exit fullscreen mode
  • graphql-core
python -m pip install graphql-core==2.3.2
Enter fullscreen mode Exit fullscreen mode
  • pymongo
python3 -m pip install pymongo==3.12.1
Enter fullscreen mode Exit fullscreen mode
  • graphene-django
pip install "graphene-django>=2.0"
Enter fullscreen mode Exit fullscreen mode

💡 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.

importing mongodb document in django

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.

Discussion (0)