如何避免使用mongodb Java驱动程序复制文档

时间:2018-08-14 21:52:34

标签: java mongodb

我需要检查将使用Java driver 3.4+添加到数据库的信息,并避免复制。 就我而言,文档将如下所示:

{
  title: "Household Portable Steam Brush Mini Iron Handheld Ironing Machine"
  url: "https://..."
  img: "..."
  price: "..."
}

假设每个文档都是唯一的。因此,我尝试使用FindIterable编写,就像这样:

long found = collection.count(Document.parse(title));
FindIterable<Document> iterable = database.getCollection("rss_feed").find(new Document("title", title)
            .append("url", url)
            .append("img", img)
            .append("price", price));
// check if feed not exists
if (found == 0) {
    Document doc = new Document("title", title)
            .append("url", url)
            .append("img", img)
            .append("price", price);
    collection.insertOne(doc);
    mongoClient.close();

    System.out.println("Feed not exists in database. Written.");
    // to check existing feed and add new feed
} else if (iterable.equals(found)) { // error
    Document doc = new Document("title", title)
            .append("url", url)
            .append("img", img)
            .append("price", price);
    collection.insertOne(doc);
    mongoClient.close();
    // if feed exists
} else {
    System.out.println("Feed exists in database.");
    mongoClient.close();
}

在这种情况下,我得到一个错误: enter image description here

还尝试创建hash-index并通过它进行检查:

 long found = collection.count(Document.parse(title));
 String indexField  = database.getCollection("rss_feed").createIndex(Indexes.hashed("_id"));

        // check if feed not exists
        if (found == 0) {
            Document doc = new Document("title", title)
                    .append("url", url)
                    .append("img", img)
                    .append("price", price);
            collection.insertOne(doc);
            mongoClient.close();

            System.out.println("Feed not exists in database. Written.");
            // added new feed
        } else if (indexField.equals(found)) { // error
            Document doc = new Document("title", title)
                    .append("url", url)
                    .append("img", img)
                    .append("price", price);
            collection.insertOne(doc);
            mongoClient.close();
            // if feed exists
        } else {
            System.out.println("Feed exists in database.");
            mongoClient.close();
        }

也得到:

enter image description here

有人知道如何检查带有字段的文档在Java中是否唯一吗?还是什么更好用?感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

如@Veeram所述,我可以使用

来检查唯一的文档
  

在找不到具有字段组合的文档时插入。

 Document found = database.getCollection("rss_feed").find(fields).first();
    if (found == null) { 
    collection.insertOne(fields); 
    mongoClient.close(); 
    System.out.println("Feed not exists in database. Written."); 
    } else { 
    System.out.println("Feed exists in database.");
     mongoClient.close(); 
    }