重复键错误集合:mydatabase.customers索引:_id_ dup键

时间:2019-09-13 13:44:42

标签: python mongodb

我要检查用户是否存在。如果用户确实存在,请勿插入。

这是我的代码:

#!/usr/bin/env python
# Python code to illustrate
# inserting data in MongoDB
from pymongo import MongoClient

try:
    myclient  = MongoClient('10.1.3.18',27017)
    print("Connected successfully!!!")
except:
    print("Could not connect to MongoDB")

# database
emp_rec1 = {
        "name":"Mr.Geek1",
        "eid":24,
        "location":"delhi"
        }
emp_rec2 = {
        "name":"Mr.Shaurya",
        "eid":14,
        "location":"delhi"
        }

emp_rec3 = {
        "name":"Mr.Shaurya111",
        "eid":141111,
        "location":"delhi111111"
        }
a=[emp_rec1,emp_rec2,emp_rec3]
mydb = myclient["mydatabase"]
#result = mydb.profiles.create_index([('user_id'],unique=True)
mycol = mydb["customers"]

#x = mycol.insert_one(a[2])
cursor = mycol.find()
for record in cursor:
    print(record)
    mydb.servers.getIndexes()
    if record['name']!="Mr.Shaurya":
        x = mycol.insert_one(a[0])
        print(record)

此代码正确吗?还是有其他解决方案?

,如果我运行两次代码,则会出现此错误:

pymongo.errors.DuplicateKeyError: E11000 duplicate key error collection: 
mydatabase.customers index: _id_ dup key: { :ObjectId('5d7b9a6bc9a8569a44a6da2c') }

如何防止MongoDB中的密钥重复? 如何使用索引?

1 个答案:

答案 0 :(得分:0)

假设eid是导致重复键错误的主键列,那么下面的代码应该可以解决您的问题。

当您遍历cursor时,您还希望遍历数组a并查看数据库eid中是否还存在cursor中的x = mycol.insert_one(a[0])。如果不存在,则将使用#!/usr/bin/env python # Python code to illustrate # inserting data in MongoDB from pymongo import MongoClient try: myclient = MongoClient('10.1.3.18',27017) print("Connected successfully!!!") except: print("Could not connect to MongoDB") # database emp_rec1 = { "name":"Mr.Geek1", "eid":24, "location":"delhi" } emp_rec2 = { "name":"Mr.Shaurya", "eid":14, "location":"delhi" } emp_rec3 = { "name":"Mr.Shaurya111", "eid":141111, "location":"delhi111111" } a=[emp_rec1,emp_rec2,emp_rec3] mydb = myclient["mydatabase"] #result = mydb.profiles.create_index([('user_id'],unique=True) mycol = mydb["customers"] #x = mycol.insert_one(a[2]) cursor = mycol.find() for record in cursor: print(record) mydb.servers.getIndexes() for i in a: if record['eid'] != i['eid']: x = mycol.insert_one(a[0]) print(record)

插入记录

代码:

customers

如果只想严格检查#!/usr/bin/env python # Python code to illustrate # inserting data in MongoDB from pymongo import MongoClient try: myclient = MongoClient('10.1.3.18',27017) print("Connected successfully!!!") except: print("Could not connect to MongoDB") # database emp_rec1 = { "name":"Mr.Geek1", "eid":24, "location":"delhi" } emp_rec2 = { "name":"Mr.Shaurya", "eid":14, "location":"delhi" } emp_rec3 = { "name":"Mr.Shaurya111", "eid":141111, "location":"delhi111111" } a=[emp_rec1,emp_rec2,emp_rec3] mydb = myclient["mydatabase"] #result = mydb.profiles.create_index([('user_id'],unique=True) mycol = mydb["customers"] #x = mycol.insert_one(a[2]) cursor = mycol.find() for record in cursor: print(record) mydb.servers.getIndexes() for i in a: if record['name'] != i['name']: x = mycol.insert_one(a[0]) print(record) 表中的用户名,则可以使用以下查询。

代码:

const customNotifierOptions: NotifierOptions = {
    position: {
        horizontal: {
            position: 'left',
            distance: 12
        },
        vertical: {
            position: 'bottom',
            distance: 12,
            gap: 10
        }
    },
    theme: 'material',
    behaviour: {
        autoHide: 5000,
        onClick: false,
        onMouseover: 'pauseAutoHide',
        showDismissButton: true,
        stacking: 4
    },
    animations: {
        enabled: true,
        show: {
            preset: 'slide',
            speed: 300,
            easing: 'ease'
        },
        hide: {
            preset: 'fade',
            speed: 300,
            easing: 'ease',
            offset: 50
        },
        shift: {
            speed: 300,
            easing: 'ease'
        },
        overlap: 150
    }
};
@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    CommonModule,
    AppRoutingModule,
    HttpClientModule,
    ReactiveFormsModule,
    MatExpansionModule,
    NotifierModule.withConfig(customNotifierOptions),
    NgbModule,
    PageHeaderModule,
    Ng2SmartTableModule,
    LanguageTranslationModule,
    DemoMaterialModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
相关问题