Set MongoDB compound index with a fixed value field

MongoDBDatabaseBig Data Analytics

For this, we will use the concept of createIndex() and create index −

> db.compoundIndexDemo.createIndex({"StudentName":1,"StudentAge":1},{unique:true});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}

Let us first create a collection with documents −

> db.compoundIndexDemo.insertOne({"StudentName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e084c1d25ddae1f53b62207")
}
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e084c5625ddae1f53b62209")
}
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e084c5b25ddae1f53b6220a")
}
> db.compoundIndexDemo.insertOne({"StudentName":"Chris","StudentAge":23});
2019-12-29T12:19:02.225+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: web.compoundIndexDemo index: StudentName_1_StudentAge_1 dup key: { : "Chris", : 23.0 } :
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: web.compoundIndexDemo index:                StudentName_1_StudentAge_1 dup key: { : \"Chris\", : 23.0 }",
   "op" : {
      "_id" : ObjectId("5e084c5e25ddae1f53b6220b"),
      "StudentName" : "Chris",
      "StudentAge" : 23
   }
})
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

Following is the query to display all documents from a collection with the help of find() method −

> db.compoundIndexDemo.find().pretty();

This will produce the following output −

{ "_id" : ObjectId("5e084c1d25ddae1f53b62207"), "StudentName" : "Chris" }
{
      "_id" : ObjectId("5e084c5625ddae1f53b62209"),
      "StudentName" : "Chris",
      "StudentAge" : 23
}
{
   "_id" : ObjectId("5e084c5b25ddae1f53b6220a"),
   "StudentName" : "Chris",
   "StudentAge" : 22
}
raja
Published on 31-Mar-2020 08:17:05
Advertisements