Model Query

Djongo lets you run MongoDB text search queries on Django CharField and TextField. To run a text search, use the text_search operator that comes built in with Djongo.

Example

from djongo.models.indexes import TextIndex
from djongo import models

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    class Meta:
        indexes = [
            TextIndex(fields=['name'])
        ]
copy code
Blog.objects.filter(name__text_search='Paul Lennon')
copy code

This will generate the pymongo command:

db.blog.find( { '$text': { '$search': "Paul Lennon" } } )
copy code

Geospatial Queries

Geospatial queries are carried out in Djongo by using a combination of the near lookup operator and the Near search object.

class Near(
    type=None,
    coordinates=None,
    minDistance=None,
    maxDistance=None)
copy code

Example

from djongo.models.indexes import TwoDSphereIndex
from djongo import models

class Location(models.Model):
    type = models.CharField(max_length=100)
    coordinates = models.ArrayField()

    class Meta:
        abstract = True

class Entry(models.Model):
    loc = models.EmbeddedField(
        model_container=Location,
    )
    class Meta:
        indexes = [
            TwoDSphereIndex(fields=['loc'])
        ]
copy code
from djongo.models import Near

search_region = Near(
    type='point',
    coordinates=[-33.9, 89.81],
    minDistance=100,
    maxDistance=200
)

Entry.objects.filter(loc__near=search_region)
copy code

This generates the following pymongo search query:

db.entry.find({
     'loc': 
        { '$near':
          {
            '$geometry': { 'type': "Point",  'coordinates': [-33.9, 89.81] },
            '$minDistance': 100,
            '$maxDistance': 200
          }
        }
   })
copy code

Specifying Query Options

Djongo lets you specify the configuration of the find command into your QuerySets. Call the configure method on a QuerySet to configure the find query. All options supported by aggregate or find can be included as kwargs. Example of valid arguments:

Arguments

ArgumentTypeDescription
allowDiskUsebooleanEnables writing to temporary files
collationCollationUsed to specify the collation. Takes an instance of Collation

Example

Blog.objects.filter(name='John Lennon').configure(hint=['-tagline'])
copy code

This generates the following pymongo find query:

db.blog.find({'name': 'John Lennon'}, hint=[('tagline', pymongo.DESCENDING)])
copy code

Tailable Cursors

Tailable cursors are used to retrieve data from capped collections. The querySet first has to be configured using configure to use a tailable cursor in the pymongo find command. Results of the querySet can only be accessed by generating an iterator by calling the QuerySet iterator

Example

iterable = Blog.objects.filter(name='John').configure(cursor_type=CursorType.TAILABLE).iterator()
for blog in iterable:
    blog.name
copy code