MongoDB Indexes - Is it possible to create both normal & compound at the same time?


Yes, you can use ensureIndex(). MongoDB provides complete support for indexes on any field in a collection of documents.

Let us create a collection with documents −

> db.demo622.ensureIndex({_id:1,Name:1,Age:1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo622.insertOne({_id:101,Name:"Chris",Age:21});
{ "acknowledged" : true, "insertedId" : 101 }
> db.demo622.insertOne({_id:102,Name:"Chris",Age:22});
{ "acknowledged" : true, "insertedId" : 102 }
> db.demo622.insertOne({_id:103,Name:"Bob",Age:21});
{ "acknowledged" : true, "insertedId" : 103 }
> db.demo622.insertOne({_id:104,Name:"Chris",Age:22});
{ "acknowledged" : true, "insertedId" : 104 }
> db.demo622.insertOne({_id:104,Name:"Chris",Age:22});
2020-04-18T12:21:18.085+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo622 index: _id_ dup key: { : 104.0 } :
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: test.demo622 index: _id_ dup key: { : 104.0 }",
      "op" : {
         "_id" : 104,
         "Name" : "Chris",
         "Age" : 22
   }
})
WriteError@src/mongo/shell/bulk_api.js:461:48
Bulk/mergeBatchResults@src/mongo/shell/bulk_api.js:841:49
Bulk/executeBatch@src/mongo/shell/bulk_api.js:906:13
Bulk/this.execute@src/mongo/shell/bulk_api.js:1150:21
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:252:9
@(shell):1:1
> db.demo622.insertOne({_id:105,Name:"Chris",Age:22});
{ "acknowledged" : true, "insertedId" : 105 }

Display all documents from a collection with the help of find() method −

> db.demo622.find();

This will produce the following output −

{ "_id" : 101, "Name" : "Chris", "Age" : 21 }
{ "_id" : 102, "Name" : "Chris", "Age" : 22 }
{ "_id" : 103, "Name" : "Bob", "Age" : 21 }
{ "_id" : 104, "Name" : "Chris", "Age" : 22 }
{ "_id" : 105, "Name" : "Chris", "Age" : 22 }

Updated on: 12-May-2020

38 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements