Home > Software engineering >  Update Data using Spring Boot
Update Data using Spring Boot

Time:10-09

{
  "_id": {
    "$numberLong": "2"
  },
  "name": "Causual",
  "categoryPackages": [
    {
      "_id": 0,
      "name": "Delhi",
      "coverPage": "https://i.pinimg.com/736x/a7/3c/bf/a73cbfbcf18054bf31ee42e6453c5d94.jpg"
    },
    {
      "_id": 0,
      "name": "Kolkata",
      "coverPage": "https://www.tourmyindia.com/images/kerala-tour-fd6.jpg"
    }
  ],
}

The above JSON data exists in MongoDB, I Have inserted the Data into MongoDB using spring boot. Now, I want to update the Data as per the below code by using the spring boot

{
  "_id": {
    "$numberLong": "2"
  },
  "name": "Causual",
  "categoryPackages": [
    {
      "_id": 0,
      "name": "Delhi",
      "coverPage": "https://i.pinimg.com/736x/a7/3c/bf/a73cbfbcf18054bf31ee42e6453c5d94.jpg"
    },
    {
      "_id": 0,
      "name": "Kolkata",
      "coverPage": "https://www.tourmyindia.com/images/kerala-tour-fd6.jpg"
    },
    {
      "_id": 0,
      "name": "Chennai",
      "coverPage": "https://www.tourmyindia.com/images/kerala-tour-fd6.jpg"
    }
  ],
  "_class": "com.traveldiaries.categories.Categories"
}

How should I Query to update it?

CodePudding user response:

Do you have a specific problem or are you asking in general?

If you've already saved your data, you probably already have a repository. You need to add a method to the interface that will define on the basis of which parameters you want to search for the object, for example:

@Repository
public interface SomeDocumentRepository extends MongoRepository<SomeDocument, String> {
   List<SomeDocument> findByName(String name);
}

Now you can query for an object, modify it, and then save it again. Similarly, you will add a new object.

SomeDocumentRepository repository;

void someMethod(){
    SomeDocument mongoDocument = repository.findByName("Causual");
    CategoryPackage categoryPackage = new CategoryPackages();
    // some operations on the object
    mongoDocument.getCategoryPackages.add(categoryPackage);
    
    repository.save(mongoDocument);
}

In short, that's it. If you have a specific problem, describe it in more detail and add a code snippet.

  • Related