javamongodbmongodb-querymongo-javamongo-collection

checking unique while inserting to mongoDB


I have a program to insert some values into the mongo db and i want to avoid repeated product_src inserting into the database. how can i set that in code? my code is

BObject doc = new BasicDBObject("product_name", bean.getProductName()).
                    append("product_url", bean.getProductURL()).
                    append("product_img", bean.getImageURL()).
                    append("product_price", bean.getPrice()).
                    append("product_src", bean.product_src).
                    append("country", bean.country));

thanks in advance.


Solution

  • You have two options to ensure the uniqueness of product_src:

    With a unique index MongoDB will throw an error when inserting a document with a duplicate value and not add the document to the collection.