I read somewhere that calling ensureIndex()
actually creates a collection if it does not exist. But the index is always on some fields, not all of them, so if I ensure an index on say { name:1 }
and then add documents to that collection that have many more fields, the index will work? I know we don't have a schema, coming from RDBMS world I just want to make sure. :) I'd like to create indexes when my website starts, but initially the database is empty. I do not need to have any data prior to ensuring indexes, is that correct?
They store the value of a specific field or more than one fields (i.e. set of fields), which are ordered by the value of the field as indicated in the index. The ensureIndex () Method. In MongoDB, we use 'ensureIndex ()' method to create an index.
To create an index in the Mongo Shell, use db. collection. createIndex() .
Along with the default index, we can create indexes on our own using the createIndex() method. This method creates one or more indexes on the specified collections.
The index or indexes to drop. To drop all indexes except the _id index and the last remaining shard key index from the collection if one exists, specify "*" . To drop a single index, specify either the index name, the index specification document (unless the index is a text index), or an array of the index name.
Deprecated since version 3.0: db.collection.ensureIndex() has been replaced by db.collection.createIndex().
Ref: https://docs.mongodb.com/manual/reference/method/db.collection.ensureIndex/
ensureIndex
will create the collection if it does not yet exist. It does not matter if you add documents that don't have the property that the index covers, you just can't use that index to find those documents. The way I understand it is that in versions before 1.7.4 a document that is missing a property for which there is an index will be indexed as though it had that property, but will a null value. In versions after 1.7.4 you can create sparse indexes that don't include these objects at all. The difference is slight but may be significant in some situations.
Depending on the circumstances it may not be a good idea to create indexes when the app starts. Consider the situation where you deploy a new version which adds new indexes when it starts up, in development you will not notice this as you only have a small database, but in production you may have a huge database and adding the index will take a lot of time. During the index creation your app will hang and you can't serve requests. You can create indexes with the background flag set to true (the syntax depends on which driver you're using), but in most cases it's better to add indexes manually, or as part of a setup script. That way you will have to think before you update indexes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With