Syntax

Text Index

  • Create a Text Index on PyMongo Create a text index on one field

    collection.create_index( [ ( 'field', pymongo.TEXT ) ] )
  • Create text indexes on multiple fields

    collection.create_index( [ ( 'field_1', pymongo.TEXT ), ( 'field_2', pymongo.TEXT ) ] )
  • Specify the weight of an indexed

    collection.create_index( 
    	[ ( 'field_1', pymongo.TEXT ), ( 'field_2', pymongo.TEXT ) ],
    	weights={ 'field_1' : 3, 'field_2' : 2 } )

Text Search Operator

  • Search

    collection.find( { '$text': {'$search' : 'VALUE' } } } )
    collection.find( { '$text': {'$search' : ' \"VALUE\" ' } } } )		# Phrase
    collection.find( { '$text': {'$search' : ' \"VALUE_1\" \"VALUE_2\" ' } } } )	# AND
    collection.find( { '$text': {'$search' : '  VALUE_1 -VALUE_2 ' } } } )	# Exclude
  • Search with options

    collection.find( { '$text': {'$search' : 'VALUE', '$caseSensitive' : True } } } )	# Case sensitive
    collection.find( { '$text': {'$search' : 'VALUE', '$language' : 'en' } } } )	# Specify a language
  • Include a score field

    collection.find( { '$text': {'$search' : 'VALUE' } }, { 'score' : { '$meta' : 'textScore' } } ) 
    collection.find( { '$text': {'$search' : 'VALUE' } }, { 'score' : { '$meta' : 'textScore' } } )	\
    		.sort( [ ('score', {'$meta': 'textScore’}) ] )	# With sorting

Last updated