0

I am trying to create a webservice which receives a json object and performs some action based on whether the object already exists as a document in my mongodb or not. If the document already exists, I have to just perform my action. If it doesn't i have to insert it first and then perform the action.

Using spring data MongoRepository or MongoTemplate, how do I check if a document already exists - using the entire document I am about to insert? I cannot use _id here. If the entire document already exists, I don't have to insert a new document. But if at least one field is different, I have to enter a new document.

Eg:

@Document (collection = "foo")
class Foo {

   @Id
   String id;
   String name;
   List<Address> address   
   ... many more attributes
}

If I get a request using an object of Foo without _id, how do I check if this already exists as a document in my mongodb collection?

Thanks!

2 Answers 2

1

I think this is what you need: Finding and modifying documents You can specify all fields that must match i.e. must be unique for all documents in the query and set upsert option to true as follows:

Query query = new Query(Criteria.where("firstName").is("Ruturaj"));
Person p = mongoTemplate.findAndModify(query, update, new FindAndModifyOptions().returnNew(true).upsert(true), Person.class);
Sign up to request clarification or add additional context in comments.

Comments

0

Why don't you index your collection on some field? Assuming you have name in all documents, query the db by name and if you dont get any result, add it. If you get a result compare it with what you have in the request. Best thing to do for comparing these 2 is to override equals method. Convert the request body into an object of the document and compare this with what you get from DB. If you cannot determine what will be passed in the request, you might have to query the DB based on whatever field is passed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.