Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Mongo Upsert nested document

I am new bie to spring framework. I have my mongo document like

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

What I want is to search document having id

"_id" : ObjectId("527242d584ae917d8bd75c7b")

and update 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 is

@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 upsert should I write to add or modify entries in intrest array[].

Please Help.

like image 817
Sumit D Avatar asked Nov 12 '13 07:11

Sumit D


2 Answers

I am using 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 what you intend to do is an update. Upsert will modify your document matching the given query if not it will create a new document , where as update will only modify your document if found. here is the reference

like image 63
Nancy Avatar answered Sep 28 '22 12:09

Nancy


I do not know about java, but all you need to do is $pushAll operator (I really hope you can find how to do this with 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")

        }] } }
);
like image 33
Salvador Dali Avatar answered Sep 28 '22 11:09

Salvador Dali