在MongoDB中创建唯一索引

8
我正在使用一个Java程序来插入MongoDB,尝试为一个字段创建唯一索引。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) {}

这是一个集合。db.t.ensureIndex({"product_src":1})的行存在问题。
请给我一个在Mongo DB中创建唯一索引的示例代码。

在db.t.ensureIndex({"product_src":1});这一行的确切问题是什么?看着这一行,它应该是t.ensureIndex({"product_src":1}); - Prashant Thakkar
语法错误在标记上,删除这个标记和红色下划线在此({"product_src":1})和t下面。 - sarath
2个回答

16

未来参考,处理此事的方法在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));
}

作为回复的补充,在第二个参数设为1的情况下,这将在字段上添加升序索引。如果您想要创建降序索引,则需要执行以下操作:`Document index = new Document("field", -1);` - GokcenG

7

您需要将DBObject传递给ensureIndex()方法。

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

然而,自版本2.12起,ensureIndex方法已经被弃用,您需要使用createIndex()代替。

db.t.createIndex(new BasicDBObject("product_src",1));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接