Mongodb avoid duplicate entries

后端 未结 6 628
情歌与酒
情歌与酒 2020-12-08 14:34

I am newbie to mongodb. May I know how to avoid duplicate entries. In relational tables, we use primary key to avoid it. May I know how to specify it in Mongodb using java?<

相关标签:
6条回答
  • 2020-12-08 14:58

    Use an index with the {unique:true} option.

    // everyone's username must be unique:
    db.users.createIndex({email:1},{unique:true});
    

    You can also do this across multiple fields. See this section in the docs for more details and examples.

    MongoDB indexes may optionally impose a unique key constraint, which guarantees that no documents are inserted whose values for the indexed keys match those of an existing document.

    If you wish for null values to be ignored from the unique key, then you have to also make the index sparse (see here), by also adding the sparse option:

    // everyone's username must be unique,
    //but there can be multiple users with no email field or a null email:
    db.users.createIndex({email:1},{unique:true, sparse:true});
    

    If you want to create the index using the MongoDB Java Driver. Try:

    Document keys = new Document("email", 1);
    collection.createIndex(keys, new IndexOptions().unique(true));
    
    0 讨论(0)
  • 2020-12-08 15:05

    As of Mongo's v3.0 Java driver, the code to create the index looks like:

    public void createUniqueIndex() {
        Document index = new Document("fieldName", 1);
        MongoCollection<Document> collection = client.getDatabase("dbName").getCollection("CollectionName");
        collection.createIndex(index, new IndexOptions().unique(true));
    }
    
    // And test to verify it works as expected
    @Test
    public void testIndex() {
        MongoCollection<Document> collection = client.getDatabase("dbName").getCollection("CollectionName");
    
        Document newDoc = new Document("fieldName", "duplicateValue");
        collection.insertOne(newDoc);
    
        // this will throw a MongoWriteException
        try {
            collection.insertOne(newDoc);
            fail("Should have thrown a mongo write exception due to duplicate key");
        } catch (MongoWriteException e) {
            assertTrue(e.getMessage().contains("duplicate key"));
        }
    }
    
    0 讨论(0)
  • 2020-12-08 15:09

    using pymongo it looks like:

    mycol.create_index("id", unique=True)
    

    where myCol is the collection in the DB

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    import pymongo
    
    myclient = pymongo.MongoClient("mongodb://localhost:27017/")
    mydb = myclient["mydatabase"]
    mycol = mydb["customers"]
    mycol.create_index("id", unique=True)
    mydict = {"name": "xoce", "address": "Highway to hell 666", "id": 1}
    x = mycol.insert_one(mydict)
    
    0 讨论(0)
  • 2020-12-08 15:11

    This can be done using "_id" field although this use is discouraged. suppose you want the names to be unique, then you can put the names in "_id" column and as you might know "_id" column is unique for each entry.

    BasicDBObject bdbo = new BasicDBObject("_id","amit");
    

    Now , no other entry can have name as "amit" in the collection.This can be one of the way you are asking for.

    0 讨论(0)
  • 2020-12-08 15:11

    I am not a Java programmer however you can probably convert this over.

    MongoDB by default does have a primary key known as the _id you can use upsert() or save() on this key to prevent the document from being written twice like so:

    var doc = {'name': 'sam'};
    db.users.insert(doc); // doc will get an _id assigned to it
    db.users.insert(doc); // Will fail since it already exists
    

    This will stop immediately duplicates. As to multithread safe inserts under certain conditions: well, we would need to know more about your condition in that case.

    I should add however that the _id index is unqiue by default.

    0 讨论(0)
  • 2020-12-08 15:12

    Theon solution didn't work for me, but this one did:

    BasicDBObject query = new BasicDBObject(<fieldname>, 1);
    collection.ensureIndex(query, <index_name>, true);
    
    0 讨论(0)
提交回复
热议问题