队
当文档不存在时,我必须创建以下文档(find_on_user)。
{
"st" : "s", //current status s=sent, d=delivered, u=undelivered, r=resent
"u" : "user",
"e" : [
//HISTORY OF EVENTS "s" - status at the time of each event
{"c": "2b3de827-ac38-4023-5950-819947858eac", "s":"s", "@":ISODate("2017-01-29T08:43:00Z")}
]
}
如果存在,对于上述连续事件,我必须仅更新事件数组。注意主文档中的最新状态(“st”)也会根据添加到数组中的新事件进行更新。
{
"st" : "r", //current status s=sent, d=delivered, u=undelivered, r=resent
"u" : "user",
"e" : [
//HISTORY OF EVENTS "s" - status at the time of each event
{"c": "2b3de827-ac38-4023-5950-819947858eac", "s":"s", "@":ISODate("2017-01-29T08:53:00Z")},
{"c": "2b3de827-ac38-4023-5950-819947858eac", "s":"u", "@":ISODate("2017-01-29T09:43:00Z")},
{"c": "2b3de827-ac38-4023-5950-819947858eac", "s":"r", "@":ISODate("2017-01-29T10:43:00Z")}
]
}
我认为我想要的是与$ push
一起db.collection.update(query, update, {upsert: true})
DBObject listItem = new BasicDBObject("e", new BasicDBObject("c","2b3de827-ac38-4023-5950-819947858eac").append("s","r").append("@",ISODate("2017-01-29T10:43:00Z"));
DBObject updateQuery = new BasicDBObject("$push", listItem);
myCol.update(findQuery, updateQuery);
如何在mongodb spring数据中一起执行此操作?请帮忙。
问题与mongodb - create doc if not exist, else push to array
非常相似但这并没有说明如何更新外部文档(“st”)以及$ push?这个答案也是处理String Json的,那可能是通过java对象吗?
来自Veeram答案:
Query query = new Query(Criteria.where("u").is("user"));
DBObject listItem = new BasicDBObject("c","2b3de827-ac38-4023-5950-819947858eac").append("s","r").append("@",new Date());
Update update = Update.update("st","r").push("e", listItem);
mongoOperations.upsert(query, update, collection_name);
因为我只有两个像“u”这样的参数,“st”Veeram在查询中使用了一个,在更新时使用了一个。当我有两个以上时会发生什么,但只有在插入时才会更新,之后只有状态(“st”)才会更新。
下面的示例“type”和“account_id”将在插入时添加,稍后更新将仅在“st”处完成。怎么解决这个?
{
"st" : "s", //current status s=sent, d=delivered, u=undelivered, r=resent
"u" : "user",
"type" : "welcome-sms",
"account_id" : "12as-df23-fg-1",
"e" : [
//HISTORY OF EVENTS "s" - status at the time of each event
{"c": "2b3de827-ac38-4023-5950-819947858eac", "s":"s", "@":ISODate("2017-01-29T08:43:00Z")}
]
我需要使用如下吗?但是type和account_id是静态的。需要仅在第一次(插入)时更新。那没关系吗?
Update updateObj = Update.update("st","r")
updateObj.set("type", "welcome-sms");
updateObj.set("account_id", "12as-df23-fg-1").push("e", listItem);
答案 0 :(得分:1)
你可以尝试这样的事情。
Query query = new Query(Criteria.where("u").is("user"));
DBObject listItem = new BasicDBObject("c","2b3de827-ac38-4023-5950-819947858eac").append("s","r").append("@",new Date());
Update updateObj = Update.update("st","r")
updateObj.setOnInsert("type", "welcome-sms");
updateObj.setOnInsert("account_id", "12as-df23-fg-1").push("e", listItem);
mongoOperations.upsert(query, updateObj, collection_name);