Spring Mongo Upsert嵌套文档

Sum*_*t D 6 java spring-mvc mongodb spring-data-mongodb

我是Spring框架的新手.我有我的mongo文件

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

我想要的是搜索有id的文件

"_id" : ObjectId("527242d584ae917d8bd75c7b")
Run Code Online (Sandbox Code Playgroud)

并将其更新为

{
    "_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")

        }

]
}
Run Code Online (Sandbox Code Playgroud)

我的域名是

@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
}
Run Code Online (Sandbox Code Playgroud)

我应该写什么upsert来添加或修改intrest array []中的条目.

请帮忙.

Nan*_*ncy 5

我正在使用spring-mongodb ..这就是我所做的

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);
Run Code Online (Sandbox Code Playgroud)

我认为你打算做的是更新.Upsert将修改与给定查询匹配的文档,否则它将创建新文档,而更新只会在找到时修改您的文档.是参考