Array Field in MongoDB

Hello Everyone, I am preparing for some mongodb interview questions and I am confused as to understand can I create an index on an array field in MongoDB? If yes, what happens in this case? Please elaborate to me.

Hello @shivam_bhatele, welcome to the MongoDB community forum.

You can create an index on a field of type array. For example, consider an array field:

colors: [ "red", "blue" , "black" ]

You can create the index on the array field with the normal index creation syntax:

db.collection.createIndex( { colors: 1 } )

In the above created index there will be three keys.

You can also create an index on a field of an array of objects. Another example array field:

contacts: [
   { name: "John", email: "john@example.com" }, 
   { name: "Pete", email: "pete@example2.com" }
 ]

Create an index on the name field:

db.collection.createIndex( { "contacts.name": 1 } )


NOTES:

  • Indexes created on array fields are called as Multikey Indexes.
  • Since, an array field can have multiple values, and with multiple documents the number of keys matter in case of arrays with large number of elements. Large sized indexes can degrade the performance of operations.
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.