我正在尝试更新Couchbase服务器5.1.1中的对象。
additionalCodes是对象列表
>>> f'the time is now {time}'
NameError: name 'time' is not defined
我在沙发上的对象是这样的:
Code(String code,String type,LocalDateTime datetime )
我确实想更新此对象,如:
{
"code": "code1";
"creationDateTime": 1534852560000,
"additionalCodes": [
{
"code": "code1",
"type": "type1",
"dateTime": 1534772384000
}
]
}
我正在尝试:
{
"code": "code1";
"creationDateTime": 1534852560000,
"additionalCodes": [
{
"code": "code1",
"type": "type1",
"dateTime": 1534772384000
},
{
"code": "code2",
"type": "type2",
"dateTime": 1534772384000
}
]
}
预先感谢
答案 0 :(得分:0)
有几种方法可以做到这一点。您可以手动将对象图转换为相应的Json *类:
// Code code = new Code(...);
JsonDocument doc = bucket.get("ID");
JsonArray curAddlCodes = doc.content().getArray("additionalCodes");
JsonObject newCode = JsonObject.create()
.put("code", code.code)
.put("type", code.type)
.put("dateTime", code.dateTime.toEpochSecond());
curAddlCodes.add(newCode);
doc = bucket.replace(doc);
或者您可以使用subdoc API仅更新additionalCodes
字段,而无需获取并发送完整文档:
bucket.mutateIn("ID")
.arrayAppend("additionalCodes", newCode)
.execute();
如果您有完整的对象图,例如:
TopLevelCode(String code, LocalDateTime creationDateTime, List<Code> additionalCodes)
那么您还有更多选择。您可以操作所需的POJO,然后使用Jackson之类的库将其序列化为JSON字符串,并将其存储在RawJsonDocument中:
// TopLevelCode tlc = new TopLevelCode(...)
ObjectMapper objectMapper = com.couchbase.client.java.transcoder.JacksonTransformers.MAPPER;
String json = objectMapper.writeValueAsString(tlc);
RawJsonDocument doc = RawJsonDocument.create("ID", json);
bucket.replace(doc);
或者,如果您的对象图是可序列化的,则可以使用SerializableDocument:
SerializableDocument doc = SerializableDocument.create("ID", tlc);
bucket.replace(doc);