如何限制在 MongoDB 中插入具有相同名稱的專案?
為此,請使用 ensureIndex() 並設定 unique:true。讓我們建立帶有文件的集合。在此,當我們嘗試插入重複的專案時,就會發生重複的鍵錯誤 −
> db.demo316.ensureIndex({"SubjectName":1},{unique:true});
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.demo316.insertOne({"SubjectName":"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e50e378f8647eb59e56205d")
}
> db.demo316.insertOne({"SubjectName":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e50e37df8647eb59e56205e")
}
> db.demo316.insertOne({"SubjectName":"MongoDB"});
2020-02-22T13:47:05.186+0530 E QUERY [js] WriteError: E11000 duplicate key error collection: test.demo316 index: SubjectName_1 dup key: { : "MongoDB" } :
WriteError({
"index" : 0,
"code" : 11000,
"errmsg" : "E11000 duplicate key error collection: test.demo316 index: SubjectName_1 dup key: { : \"MongoDB\" }",
"op" : {
"_id" : ObjectId("5e50e381f8647eb59e56205f"),
"SubjectName" : "MongoDB"
}
})
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.demo316.find();
這將產生以下輸出 −
{ "_id" : ObjectId("5e50e378f8647eb59e56205d"), "SubjectName" : "MySQL" }
{ "_id" : ObjectId("5e50e37df8647eb59e56205e"), "SubjectName" : "MongoDB" }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP