Spring Mongo Upsert嵌套文档

时间:2013-11-12 07:20:49

标签: java mongodb spring-mvc spring-data-mongodb

我是春天框架的新手。我有我的mongo文件,如

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

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

"_id" : ObjectId("527242d584ae917d8bd75c7b")

并将其更新为

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

        }

]
}

我的域名

@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
}

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

请帮助。

1 个答案:

答案 0 :(得分: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);

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