Use pymongo in django directly

11,048

Solution 1

you may use pyMongo like below code

from pymongo import MongoClient


class MongoConnection(object):

    def __init__(self):
        client = MongoClient('localhost', 27017)
        self.db = client['database_name']

    def get_collection(self, name):
        self.collection = self.db[name]

we create a connection as per our need.

class MyCollection(MongoConnection):

    def __init__(self):
       super(MyCollection, self).__init__()
       self.get_collection('collection_name')

    def update_and_save(self, obj):
       if self.collection.find({'id': obj.id}).count():
           self.collection.update({ "id": obj.id},{'id':123,'name':'test'})
       else:
           self.collection.insert_one({'id':123,'name':'test'})

    def remove(self, obj):
        if self.collection.find({'id': obj.id}).count():
           self.collection.delete_one({ "id": obj.id})

Now you just need to call like below.

my_col_obj = MyCollection()
obj = Mymodel.objects.first()
my_col_obj.update_and_save(obj)
my_col_obj.remove(obj)

Solution 2

I am currently working on a very similar problem.

You are right, mongoengine does not support Django, but, as far as I know, pymongo does not support it too. At least mongoengine have plans to support it some day. If you are familiar with Django, it has model-like things - documents. They are easy to work with - this is actually a full working ORM. You don't get that with pymongo and if you are going to build a large, reusable application, you will end up writing ORM yourself or have spaghetti code. This was the reason for me to use mongoengine.

In your settings.py you should include this code:

from mongoengine import connect
connect('your_database')

If you still want to use pymongo for some reason, your code should look like this:

from pymongo import MongoClient
client = MongoClient()
Share:
11,048
Jimmy Lin
Author by

Jimmy Lin

Updated on June 27, 2022

Comments

  • Jimmy Lin
    Jimmy Lin almost 2 years

    I am building a website using Django and MongoDB. There are 2 popular API framework that we can use to connect Django and MongoDB, one is mongoengine and the other is django-mongodb-engine.

    Because the latest mongoengine is not supported Django anymore Document, and django-mongodb-engine needs another django-nonrel package which makes the development environment a little bit complicate.

    I am wondering, if I could use Pymongo to connect Django and MongoDB directly.

    Is there anyone who have the same experience that could share? and how to set the db in setting.py in Django to make the db public?