【发布时间】:2017-06-17 17:56:34
【问题描述】:
团队,
当文档不存在时,我必须创建以下文档(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")}
]
}
我想我想要的是 upsert 和 $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 data 中一起做这个?请帮忙。
问题与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 使用了一个用于查询和一个用于更新。当我有两个以上时会发生什么,但那些只在插入时更新,以后只有 status("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);
【问题讨论】:
-
有点相关 stackoverflow.com/questions/15436542/… 但没有完全回答我的问题。
标签: mongodb spring-data