MongoDB and upsert problem

I have two models:

1-ResourceVacation:

    @Id
    private String resourceID;
    private List<Vacation> vacationList;

2-vacation:

@Id
private String id;
private String start;
private String title;

JSON for ResourceVacation after I pasted into it:

{"_id": "foo", "_class": "com.test.model.ResourceVacation", "vacationList": [{"_id": "1", "start": "abc", "title": " test "}]}

I need to update the vacation, and if I need a resource that already exists in ResourceVacation, replace "vacationList" with json with the one I have.

ELSE: Insert New ResourceVacation Resource

    Vacation vacation = new Vacation("a", "a", "a");
    List<Vacation> list = new ArrayList<Vacation>();
    list.add(vacation);

    ResourceVacation resourceVacation = new ResourceVacation("foo", list);
    MongoOperations mongoOperations = mongoConfiguration.getMongoTemplate();
    DBCollection db = mongoOperations.getCollection("resourceVacation");

    BasicDBObject myQuery = new BasicDBObject("_id", resourceVacation.getResourceID());
    BasicDBObject myUpdate = new BasicDBObject("push ", new BasicDBObject("vacationList",
            resourceVacation.getVacationList()));

    db.update(myQuery, myUpdate);

I get the following exception:

java.lang.IllegalArgumentException: can't serialize class com.springway.model.Vacation
+2
source share
2 answers

-, , upsert. Java API , db.update true.

   db.update(com.mongodb.DBObject, com.mongodb.DBObject, boolean /*upsert */, boolean /* multi */)

$push - , , mongo:

db.collection.update( {"resourceVacation":resourceID}, {$set:{"vacationList":[...]}, true)

: resourceVacation resourceID , "vacationList" , . , .

Java API , .

, MongoTemplate Spring. , , , upserts. . , , .

, upsert , .

+1

updateFirst. .

0

Source: https://habr.com/ru/post/1607872/


All Articles