Create geospatial and type index together in MongoDB? - 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

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})

Related

Can a query still use an index to sort a field if the index was not the one chosen in the winning plan?

I have a compound index and an index on a single field A. If in a find query, the compound index was chosen as the winning plan, and the results are sorted by the field A, will field A's index be used to sort it?
Unfortunately, no.
MongoDB cannot use different indexes for sorting and document selection.
See https://www.mongodb.com/docs/manual/tutorial/sort-results-with-indexes/#use-indexes-to-sort-query-results
Note that it can use a compound index for sorting, i.e. if the compound index were on {a:1, otherfield:1}, that index can be used for selection by multiple fields, and sorting by a.

How to drop selected multiple indexes for a collection in mongodb?

I want to drop multiple selected indexes by name using query in mongodb
I tried using dropIndex to drop multiple indexes.But this is deleting only first index i.e,index_1
db.getCollection('test').dropIndex( "index_1", "index_2" )
should delete index_1 and index_2
db.collection.dropIndexes()
Drops all indexes other than the required index on the _id field.
The db.collection.dropIndex() method takes the following parameter:
index (string or document)
Specifies the index to drop. You can specify the index either by the index name or by the index specification document.
So, it means you can not specify two indexes. To delete two indexes call db.collection.dropIndex() twice.
To obtain a list of documents that identify and describe the existing indexes on the collection use
db.collection.getIndexes()

How to index and sorting with Pagination using custom field in MongoDB ex: name instead of id

https://scalegrid.io/blog/fast-paging-with-mongodb/
Example : {
_id,
name,
company,
state
}
I've gone through the 2 scenarios explained in the above link and it says sorting by object id makes good performance while retrieve and sort the results. Instead of default sorting using object id , I want to index for my own custom field "name" and "company" want to sort and pagination on this two fields (Both fields holds the string value).
I am not sure how we can use gt or lt for a name, currently blocked on how to resolve this to provide pagination when a user sort by name.
How to index and do pagination for two fields?
Answer to your question is
db.Example.createIndex( { name: 1, company: 1 } )
And for pagination explanation the link you have shared on your question is good enough. Ex
db.Example.find({name = "John", country = "Ireland"}). limit(10);
For Sorting
db.Example.find().sort({"name" = 1, "country" = 1}).limit(userPassedLowerLimit).skip(userPassedUpperLimit);
If the user request to fetch 21-30 first documents after sorting on Name then country both in ascending order
db.Example.find().sort({"name" = 1, "country" = 1}).limit(30).skip(20);
For basic understand of Indexing in MonogDB
Indexes support the efficient execution of queries in MongoDB. Without indexes, MongoDB must perform a collection scan, i.e. scan every document in a collection, to select those documents that match the query statement. If an appropriate index exists for a query, MongoDB can use the index to limit the number of documents it must inspect.
Indexes are special data structures, that store a small portion of the collection’s data set in an easy to traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field.
Default _id Index
MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index on the _id field.
Create an Index
Syntax to execute on Mongo Shell
db.collection.createIndex( <key and index type specification>, <options> )
Ex:
db.collection.createIndex( { name: -1 } )
for ascending use 1,for descending use -1
The above rich query only creates an index if an index of the same specification does not already exist.
Index Types
MongoDB provides different index types to support specific types of data and queries. But i would like to mention 2 important types
1. Single Field
In addition to the MongoDB-defined _id index, MongoDB supports the creation of user-defined ascending/descending indexes on a single field of a document.
2. Compound Index
MongoDB also supports user-defined indexes on multiple fields, i.e. compound indexes.
The order of fields listed in a compound index has significance. For instance, if a compound index consists of { name: 1, company: 1 }, the index sorts first by name and then, within each name value, sorts by company.
Source for my understanding and answer and to know more about MongoDB indexing MongoDB Indexing

MongoDB Indexing: Multiple single-field vs single compound?

I have a collection of geospatial+temporal data with a few additional properties, which I'll be displaying on a map. The collection has a few million documents at this point, and will grow over time.
Each document has the following fields:
Location: [geojson object]
Date: [Date object]
ZoomLevel: [int32]
EntryType: [ObjectID]
I need to be able to rapidly query this collection by any combination of location (generally a geowithin query), Date (generally $gte/$lt), ZoomLevel and EntryType.
What I'm wondering is: Should I make a compound index containing all four fields, or a single index for each field, or some combination thereof? I read in the MongoDB docs the following:
For a compound index that includes a 2dsphere index key along with
keys of other types, only the 2dsphere index field determines whether
the index references a document.
...Which sounds like it means having the 2dsphere index for Location be part of a compound index might be pointless?
Any clarity on this would be much appreciated.
For your use case you will need to use multiple indexes.
If you create one index covering all fields of your documents your queries will only be able to use it when they include the first field in the index.
Since you need to query by any combination of these four fields I suggest you to analyze your data access patterns and see exactly what filters are you actually using and create specific index for each one or group of them.
EDIT: For your question about 2dsphere, it does make sense to make them compound.
This note refers to the 'sparse' option. Sparse index references only documents that contains the index fields, for 2dspheres the only documents that will be left out is the ones that do not contain the geojson/point array.

What does the digit "1" mean when creating indexes in mongodb

I am new to mongodb and want to make indexes for a specific collection. I have seen people use a digit "1" in front of the field name when they want to create an index. for example:
db.users.ensureIndex({user_name: 1})
now I want to know what does this digit mean and is it necessary to use it?
It's the type of index. MongoDB supports different kinds of indexes. However, only the first two indexes can be combined to a compound index.
1: Ascending binary-tree index.
-1: Descending binary-tree index. Very similar to the default index but the difference can matter for the behavior of compound indexes.
"hashed": A hashtable index. Very fast for lookup by exact value, especially in very large collections. But not usable for inexact queries ($gt, $regex or similar).
"text": A text index designed for searching for words in strings with natural language.
"2d": A geospatial index on a flat plane
"2dsphere": A geospatial index on a sphere
For more information, see the documentation of index types.
It defines the index type on that specefic field. For example the value of 1 creates an index with ascending order, while the value -1 create the index with descending order.
For more information, see the Manual