Mongodb avoid duplicate entries

后端 未结 6 684
情歌与酒
情歌与酒 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 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 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 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"));
        }
    }
    

提交回复
热议问题