nosheyakku
nosheyakku

Reputation: 346

What is the best index to create for such a collection in MongoDB?

I have a collection with documents like this:

{
  "_id":{
    "$oid":"60c5316cbc885e00c6e5abeb"
  },
  "name":"<name>",
  "addedAt":{
    "date":{
      "$date":"2021-06-12T22:13:00.316Z"
    },
    "timestamp":1623535980.316648
  },
  "lastUsed":{
    "date":{
      "$date":"2021-06-22T14:17:23.339Z"
    },
    "timestamp":1624371443.339323
  },
  "connStr":"http://<user>:<pwd>@<host>:<port>",
  "resetIpUri":"http://<host>:<port>/api/changeIP?apiToken=<token>",
  "lastResetIP":1623535980.316648
}

And pretty simple queries:

db.collection.find({connStr: <connStr>})
db.collection.find({}).sort({"lastUsed.timestamp": 1})

But I'm not quite sure if I need to use a text index for the field conStr, or a regular one? I cannot understand how text indexes work, do I always need to use them when I have a task to find a document by its value, if so, should I use text indexes for integer or float fields?

Upvotes: 0

Views: 213

Answers (1)

hhharsha36
hhharsha36

Reputation: 3349

Text Indexes and regular Indexes are entirely different and should be used under entirely different scenarios.

Go for Normal Indexing if:

You will be matching the exact string value of a key or you will be using Regex operations on the string value stored.

The Normal Index is what you are looking for.

Go for Text Indexing if:

You want the values of a key to be stemmed for searching purposes. For Example The stemming of the root word like are: likes, liked, likely, liking, etc. All these are stems of the root word like.

If you want a key value to be searchable, like textbook name or description, you can make use of the text indexing, and perform a text search on the key, which will perform a stem search of all the words.

Note: I am no MongoDB Text Index expert and just have a vague idea of what it is. Any corrections and edits are welcomed.

Upvotes: 1

Related Questions