Spring Attached Document Mongo Upsert

I am the new bie for spring frame. I have my document in mongo, how

{ "_id" : ObjectId("527242d584ae917d8bd75c7b"), "postTitle" : "Car", "postDesc" : "rent", "owner" : ObjectId("526a588f84aed6f41cca10bd"), "intrest" : [] } 

I want to search for document with id

 "_id" : ObjectId("527242d584ae917d8bd75c7b") 

and upgrade it to

 { "_id" : ObjectId("527242d584ae917d8bd75c7b"), "postTitle" : "Car", "postDesc" : "rent", "owner" : ObjectId("526a588f84aed6f41cca10bd"), "intrest" : [ { "userId" : ObjectId("526a587d84aed6f41cca10bc"), "timestamp" : ISODate("2013-10-31T11:45:25.256Z") }, { "userId" : ObjectId("526a587d84aed6f41cca10bc"), "timestamp" : ISODate("2013-11-31T11:55:25.256a") } ] } 

my domain

 @Document public class Post { @Id private ObjectId _id; private String postTitle; private String postDesc; private ObjectId owner=Global.getCurruser(); private List<Intrest> intrest = new ArrayList<Intrest>(); // Getters and setters } @Document public class Intrest { private ObjectId userId; private Date timestamp; // Getters and setters } 

What you need to write to add or modify entries in the intrest [] array.

Please, help.

+6
source share
2 answers

I use spring-mongodb .. Here is what I do

 Intrest insertObj = new Insert(); //initilize insert obj here .. Update args = new Update(); args.addToSet("intrest",insertObj); Query query = new Query(Criteria.where("id").is("527242d584ae917d8bd75c7b")); // if u want to do upsert mongoOperation.findAndModify(query, args, FindAndModifyOptions.options().upsert(true), Post.class); //if u want to just update mongoOperation.findAndModify(query, args, Post.class); 

I think you intend to do this update. Upsert will modify your document matching this request if it does not create a new document, since the update will only modify your document if it is found. here is a link

+5
source

I don't know about java, but all you need to do is $ pushAll (I really hope you can find how to do this with the java driver).

 db.collection.update( {"_id" : ObjectId("527242d584ae917d8bd75c7b")}, { $pushAll: { intrest: [ { "userId" : ObjectId("526a587d84aed6f41cca10bc"), "timestamp" : ISODate("2013-10-31T11:45:25.256Z") }, { "userId" : ObjectId("526a587d84aed6f41cca10bc"), "timestamp" : ISODate("2013-11-31T11:55:25.256a") }] } } ); 
+2
source

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


All Articles