Cara menggunakan mongodb unique field

Tanggal dipublikasikan: 27 April, 2022

The unique partial indexes feature allows you more flexibility to specify exactly which fields in which documents you’d like to index, all while enforcing uniqueness of that field’s value. This feature is used by specifying a partialFilterExpression when creating the index along with a 'unique' constraint in your Azure Cosmos DB API for MongoDB index. This results in the unique constraint being applied only to the documents that meet the specified filter expression. 

Learn more. 

Last update on August 19 2022 21:51:25 (UTC/GMT +8 hours)

db.collection.createIndex

The db.collection.createIndex() method is used to builds an index on a collection.

Table of Contents

  • db.collection.createIndex
  • Example: Create an Ascending Index on a Single Field
  • Example: Create an Index on a Multiple Fields
  • Can we create multiple index on same collection in MongoDB?
  • How do I create a unique compound index in MongoDB?
  • Can I create an unique index?
  • How do I change an existing index in MongoDB?

Syntax:

db.collection.createIndex(keys, options)

Parameters:

NameDescriptionRequired /
Optional
Type
keys A document that contains the field and value pairs where the field is the index key and the value describes the type of index for that field. For an ascending index on a field, specify a value of 1; for the descending index, specify a value of -1.
MongoDB supports several different index types including text, geospatial, and hashed indexes. See Index Types for more information.
Required document
options A document that contains a set of options that controls the creation of the index. Optional document

Options

The following options are available for all index types unless otherwise specified:

FieldTypeDescription
background boolean Optional. Builds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false.
unique boolean Optional. Creates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.
name string Optional. The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.
Whether user specified or MongoDB generated, index names including their full namespace (i.e. database.collection) cannot be longer than the Index Name Limit.
sparse boolean Optional. If true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false. See Sparse Indexes for more information.
expireAfterSeconds integer Optional. Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. See Expire Data from Collections by Setting TTL for more information on this functionality. This applies only to TTL indexes.
v index version Optional. The index version number. The default index version depends on the version of mongod running when creating the index. Before version 2.0, this value was 0; versions 2.0 and later use version 1, which provides a smaller and faster index format. Specify a different index version only in unusual situations.
storageEngine document Optional. Allows users to specify the configuration to the storage engine on a per-index basis when creating an index. The value of the storageEngine option should take the following form: { <storage-engine-name>: <options> } Storage engine configuration specified when creating indexes are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.

Sample document in the restaurants collection:


{
  "address": {
     "building": "1007",
     "coord": [ -73.856077, 40.848447 ],
     "street": "Morris Park Ave",
     "zipcode": "10462"
  },
  "borough": "Bronx",
  "cuisine": "Bakery",
  "grades": [
     { "date": { "$date": 1393804800000 }, "grade": "A", "score": 2 },
     { "date": { "$date": 1378857600000 }, "grade": "A", "score": 6 },
     { "date": { "$date": 1358985600000 }, "grade": "A", "score": 10 },
     { "date": { "$date": 1322006400000 }, "grade": "A", "score": 9 },
     { "date": { "$date": 1299715200000 }, "grade": "B", "score": 14 }
  ],
  "name": "Morris Park Bake Shop",
  "restaurant_id": "30075445"
}
......

Example: Create an Ascending Index on a Single Field

The following example creates an ascending index on the field cuisine.

> db.restaurants.createIndex( { "cuisine": 1 } );
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1

Example: Create an Index on a Multiple Fields

The following example creates a compound index on the cuisine field (in ascending order) and the zipcode field (in descending order.)

> db.restaurants.createIndex( { "cuisine": 1 , "address.zipcode": -1 } );
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 2,
        "numIndexesAfter" : 3,
        "ok" : 1
}

Retrieve the restaurants data from here

Behavior

The createIndex() method has the behaviors described here.

  • To add or change index options you must drop the index using the dropIndex() method and issue another createIndex() operation with the new options.
    If you create an index with one set of options, and then issue the createIndex() method with the same index fields and different options without first dropping the index, createIndex() will not rebuild the existing index with the new options.
  • If you call multiple createIndex() methods with the same index specification at the same time, only the first operation will succeed, all other operations will have no effect.
  • Non-background indexing operations will block all other operations on a database.
  • MongoDB will not create an index on a collection if the index entry for an existing document exceeds the Maximum Index Key Length.

Previous: db.collection.count() method
Next: db.collection.dataSize() method

Can we create multiple index on same collection in MongoDB?

Multiple index options can be specified in the same document. However, if you specify multiple option documents the db. collection. createIndexes() operation will fail.

How do I create a unique compound index in MongoDB?

To create a unique index, use the db. collection. createIndex() method with the unique option set to true .

Can I create an unique index?

You cannot create a unique index on a single column if that column contains NULL in more than one row. Similarly, you cannot create a unique index on multiple columns if the combination of columns contains NULL in more than one row. These are treated as duplicate values for indexing purposes.

How do I change an existing index in MongoDB?

To modify an existing index in the MongoDB Shell, you need to drop and recreate the index. The exception to this rule is TTL indexes, which can be modified via the collMod command in conjunction with the index collection flag.