Search code examples
mongodbindexinggeospatial2dsphere

Create geospatial and type index together in MongoDB?


I want to use two indexes from different index types (2dsphere and text) by using this command :

db.mycoll.createIndex({"@geolocationable":"2dsphere",name:"text"})

but I get the following Error:

"errmsg" : "bad index key pattern { @geolocationable: \"2dsphere\", name: \"text\" }: Can't use more than one index plugin for a single index."

I read MongoDB Text and 2D compound index but I'm not sure that why I can't create 2dsphere and text index in one collection.

I don't mean that I want to use of both indexes in one query while I want to create this indexes in order to use from them in separate queries individually


Solution

  • Edit: Modified to answer the updated question.

    If both the fields are to be used in queries separately, then you can create 2 different indexes instead of the compound index.

    The geospatial index:

    db.mycoll.createIndex({"@geolocationable":"2dsphere"})
    

    The text index:

    db.mycoll.createIndex({name:"text"})
    

    Also, from docs note that

    A collection can have at most one text index.

    While creating a compound index, text index can not be grouped with a multi or geospatial index. It is a compound index restriction.

    From the docs:

    A compound text index cannot include any other special index types, such as multi-key or geospatial index fields.

    However, if you are not going to perform case insensitive searches on name field, you can create the compound index with a normal index instead of a text index.

    db.mycoll.createIndex({"@geolocationable":"2dsphere",name:1})