7

我正在使用 java 程序进行 mongo db 插入,试图为字段创建唯一索引。product_src 是我集合中的一个字段,我想将其设置为唯一索引以避免重复插入。我正在尝试以下代码,但显示语法错误这是什么问题。

DB db;
    try {
        sample = new MongoClient("myIP",PORT);
        db = sample.getDB("client_mahout");
        t = db.getCollection("data_flipkart_in_avoid_duplicate_checking");
        System.out.println("enter the system ip");
        db.t.ensureIndex({"product_src":1});
    } catch (Exception e) {}

t 是集合。行 db.t.ensureIndex({"product_src":1}); 有问题

请给我一个示例代码如何在 mongo DB 中创建唯一索引

4

2 回答 2

15

为了将来参考,在 Java Mongo 驱动程序 v3.0+ 中处理此问题的方法是:

public void createUniqueIndex() {
    Document index = new Document("field", 1);
    MongoCollection<Document> collection = client.getDatabase("db").getCollection("Collection");
    collection.createIndex(index, new IndexOptions().unique(true));
}
于 2016-01-14T16:37:26.043 回答
7

您需要将 a 传递DBObjectensureIndex()方法。

db.t.ensureIndex(new BasicDBObject("product_src",1))

但是,该ensureIndex方法自 version 以来已被弃用2.12,您需要createIndex()改用。

db.t.createIndex(new BasicDBObject("product_src",1));
于 2014-12-31T10:54:55.193 回答