0

I want to insert the documents without any duplicates .I tried with createIndex but MongoDB can enforce a uniqueness constraint on a ranged shard key index. Through the use of a unique index on the shard key.For an already-sharded collection, you cannot create unique indexes on other fields.We cannot specify a unique constraint on a hashed index . So I tried with upsert with UpdateOne but it is failing with the java.lang.IllegalArgumentException: Invalid BSON field name Orders . Here The request is coming as below Document with the Post method . Can anyone help how to avoid the duplicate transactions while inserting the documents without index creation

{ 
    "_id" : ObjectId("3456defctuijk"), 
    "Orders" : {
        "Type" : {
            "key" : "change", 
            "value" : "red"
        },  
        "Amount" : {         
            "amount" : 65
        }, 
       
    },     
    "Type" : {        
        "IdentifierValue" : "Sample.txt",       
    }, 
}

 @RequestMapping(method = RequestMethod.POST, value = "/sample")
    @ResponseBody
    public boolean createService(@Valid @RequestBody Document... docs) {
        MongoDatabase database = this.mongoClient.getDatabase("database");
        MongoCollection<Document> collection = database.getCollection("Sample");

        List<Document> documentList = new ArrayList<>(docs.length);
     
        for (Document doc : docs) {    
            documentList.add(Document.parse(doc.toJson()));
        }

       Document doc= (Document) documentList.iterator().next().get("Type");
        String identifierValue = (String) doc.get("IdentifierValue");
        Bson filter = Filters.eq("Type.IdentifierValue", IdentifierValue);
         Bson update = Updates.combine(documentList);
        UpdateOptions options = new UpdateOptions().upsert(true);
        collection.updateOne(filter,documentList,options);

    }
Rose
  • 89
  • 5
  • 18

0 Answers0