From e3c43a68f75f21872526deeb7314effb11c7b50b Mon Sep 17 00:00:00 2001 From: Franco Colmenarez Date: Wed, 15 Sep 2021 13:30:34 -0500 Subject: [PATCH] Indexes --- README.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/README.md b/README.md index e95a31f..d242bd7 100644 --- a/README.md +++ b/README.md @@ -330,3 +330,69 @@ Returns: { "_id" : "Charmander", "total" : 20 } ``` [More SQL vs Mongo examples](https://docs.mongodb.com/manual/reference/sql-aggregation-comparison/) + +# Indexes for faster searching +Get indexes of a collection: +``` +> db.pokemons.getIndexes() +``` +It will return `_id` because it's the index by default +``` +[{ + "v" : 2, + "key" : { + "_id" : 1 + }, + "name" : "_id_" +}] +``` + +## Create an index +Create type text index +``` +> db.pokemons.createIndex({name: "text"}) +``` +Will return +``` +{ + "numIndexesBefore" : 1, + "numIndexesAfter" : 2, + "createdCollectionAutomatically" : false, + "ok" : 1 +} +``` +And now we will get more indexes: +``` +> db.pokemons.getIndexes() + +[ + { + "v" : 2, + "key" : { + "_id" : 1 + }, + "name" : "_id_" + }, + { + "v" : 2, + "key" : { + "_fts" : "text", + "_ftsx" : 1 + }, + "name" : "name_text", + "weights" : { + "name" : 1 + }, + "default_language" : "english", + "language_override" : "language", + "textIndexVersion" : 3 + } +] +``` + +## Searching by text +``` +> db.pokemons.find({$text: {$search: "Pikachu"}}) + +{ "_id" : ObjectId("61422737f096f662d9ea826d"), "name" : "Charmander", "level" : 20, "pokedexId" : 2, "type" : [ "fire" ] } +```