MongoDB
 Computer >> コンピューター >  >> プログラミング >> MongoDB

MongoDBのコレクションに一意のインデックスであるフィールドを追加しますか?


一意のインデックスの場合、インデックスの作成時にunique-trueを設定します。ドキュメントを使用してコレクションを作成しましょう-

> db.demo658.createIndex({FirstName:1},{unique:true,sparse:true});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
>
> db.demo658.insertOne({"FirstName":"John","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea067144deddd72997713d9")
}
> db.demo658.insertOne({"FirstName":"Adam","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea0671c4deddd72997713da")
}
> db.demo658.insertOne({"FirstName":"John","LastName":"Doe"});
2020-04-22T21:17:46.072+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: onlinecustomertracker.demo658 index: FirstName_1 dup key: { : "John" } :
WriteError({
   "index" : 0,
   "code" : 11000,
   "errmsg" : "E11000 duplicate key error collection: onlinecustomertracker.demo658 index: FirstName_1 dup key: { : \"John\" }",
   "op" : {
      "_id" : ObjectId("5ea067224deddd72997713db"),
      "FirstName" : "John",
      "LastName" : "Doe"
   }
})
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

find()メソッドを使用してコレクションからすべてのドキュメントを表示する-

> db.demo658.find();

これにより、次の出力が生成されます-

{ "_id" : ObjectId("5ea067144deddd72997713d9"), "FirstName" : "John", "LastName" : "Smith" }
{ "_id" : ObjectId("5ea0671c4deddd72997713da"), "FirstName" : "Adam", "LastName" : "Smith" }

  1. MongoDBコレクションにインデックスを作成しますか?

    インデックスを作成するには、MongoDBでcreateIndex()を使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo702.createIndex({"details.id":1}); {    "createdCollectionAutomatically" : true,    "numIndexesBefore" : 1,    "numIndexesAfter" : 2,    &q

  2. MongoDBコレクション内のすべてのドキュメントに新しいフィールドを追加する方法

    新しいフィールドを追加するには、MongoDBで$addFieldsを使用します。ドキュメントを使用してコレクションを作成しましょう- > db.demo712.insertOne({"Name":"John"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5ea85f675d33e20ed1097b82") } > db.demo712.insertOne({"