0% completed
Multikey indexes in MongoDB are used to index fields that contain arrays. These indexes allow MongoDB to index each element of the array, which enables efficient querying and sorting based on array values. Multikey indexes are particularly useful for applications that store lists or sets of values within a single field.
db.collection.createIndex({ <arrayField>: <type> }, { <option1>: <value1>, <option2>: <value2>, ... })
Let's insert some documents into the books
collection:
db.books.insertMany([ { title: "To Kill a Mockingbird", authors: ["Harper Lee"], genres: ["Fiction", "Classic"], published: 1960 }, { title: "1984", authors: ["George Orwell"], genres: ["Dystopian", "Science Fiction"], published: 1949 }, { title: "Moby Dick", authors: ["Herman Melville"], genres: ["Adventure", "Classic"], published: 1851 }, { title: "The Great Gatsby", authors: ["F. Scott Fitzgerald"], genres: ["Fiction", "Classic"], published: 1925 }, { title: "War and Peace", authors: ["Leo Tolstoy"], genres: ["Historical", "Classic"], published: 1869 } ])
Create a multikey index on the genres
field:
db.books.createIndex({ genres: 1 })
Explanation:
db.books.createIndex({ genres: 1 })
: This command creates a multikey index on the genres
array field. This index will speed up queries that filter or sort by the elements of the genres
array.Example 1: Query by Array Element
db.books.find({ genres: "Classic" })
Explanation:
genres
field to quickly locate documents where one of the genres
is "Classic".Example 2: Query with Multiple Array Elements
db.books.find({ genres: { $all: ["Fiction", "Classic"] } })
Explanation:
genres
array contains both "Fiction" and "Classic".Multikey indexes in MongoDB are essential for optimizing queries that involve array fields. By indexing each element of an array, MongoDB can efficiently retrieve and sort documents based on array contents.
.....
.....
.....