我在队友的下面给出了python查询,将其更改为Java实现。
dataCollection = MONGOC['DATABASE_NAME']['COLLECTION']
requests = []
for doc in DATA:
requests.append(UpdateOne(
{
'rId': doc['id'],
'ts': doc['ts']
},
{
'$push': {
'data': {
'$each': [{'ms': doc['ts'], 'data': doc['data']}],
'$sort': {'ms': 1}
}
},
'$setOnInsert': {
'ts': doc['ts'].replace(microsecond=0, second=0),
'regId': doc['id']
}
}, upsert=True)
)
rr = dataCollection.bulk_write(requests, ordered=False)
请求对象采用列表的形式。以下是一个示例。
[ {
"id" : "582",
"value" : 5.125,
"ts" : "2017-05-01T00:55:51.326Z"
},
{
"id" : "582",
"value" : 5.625,
"ts" : "2017-05-01T00:55:52.326Z"
}
]
执行java代码后,数据库文档应如下所示,如果文档已经存在,则应附加数据数组。
{
"_id" : ObjectId("XXX"),
"rId" : ObjectId("582"),
"ts" : ISODate("2017-05-01T00:55:00.000+0000"),
"data" : [
{
"data" : 5.125,
"ms" : NumberInt(2279)
},
{
"data" : 5.625,
"ms" : NumberInt(2454)
}
]
}
我的java代码实现将json数组转换为List of Objects。然后我迭代这个列表并执行更新操作。:
DBCollection collection = getDataBaseCollection();
BulkWriteOperation bulkOperation = collection.initializeUnorderedBulkOperation();
for(DataList req : regDataList) {
String timeStamp = req.getTs();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
LocalDateTime ts = LocalDateTime.parse(timeStamp, formatter);
Date out = Date.from(ts.withNano(0).withSecond(0).atZone(ZoneId.systemDefault()).toInstant());
BasicDBObject o1 = new BasicDBObject();
o1.append("ms", getMilliSeconds(ts.getSecond(), ts.getNano()));
o1.append("data", Double.valueOf(req.getValue()));
BasicDBList a = new BasicDBList();
a.add(o1);
DBObject aa = new BasicDBObject("regId", new ObjectId(req.getId())).append("ts", out);
DBObject dataList = new BasicDBObject("data", new BasicDBObject("$each", a)).append("sort", new BasicDBObject("ts ", 1));
DBObject updateQuery = new BasicDBObject("$push", dataList).append("$setOnInsert", new BasicDBObject("regId", new ObjectId(req.getId())).append("ts", out));
bulkOperation.find(aa).upsert().updateOne(updateQuery);
bulkOperation.execute();
}
添加第一个文档,但下一个文档不会附加到集合中的数据数组。 java代码有什么问题?另外我想知道我是否可以使用批量操作一次更新所有文档而不是单独更新。