[英]MongoDB Java driver edit a cursor after it has been retrieved
In my MongoDB Java driver I retrieve some documents with a query. 在我的MongoDB Java驱动程序中,我通过查询检索了一些文档。
DBCursor cursor = dbCollection.find(query).sort(new BasicDBObject("date", -1));
return JSON.serialize(cursor);
This works fine it returns the following: 这工作正常,它返回以下内容:
{
"isSuccessful": true,
"result": [
{
"date": {
"$date": "2014-11-26T23:00:00.000Z"
},
value: 20
}
]
}
But: I want to edit the field $date using 但是:我想使用
SimpleDateFormat
I've tried this: 我已经试过了:
DBCursor cursor = dbCollection.find(query).sort(new BasicDBObject("date", -1));
while(cursor.hasNext()){
DBObject dbo = cursor.next();
dbo.put("date", simpleDate.format(dbo.get("date")));
}
return JSON.serialize(cursor);
But the while loop doesn't affect the returned result. 但是while循环不会影响返回的结果。
It just gives the same result back. 它只是返回相同的结果。 How do I change the date field and then return it? 如何更改日期字段然后返回? Also i've put the following line: 我也把以下行:
simpleDate.format(dbo.get("date"))
In a System.out.printline(""); 在System.out.printline(“”);中
And this prints out "27-11-2014", just like i want it. 并打印出“ 27-11-2014”,就像我想要的一样。
I solved it by doing the following: 我通过执行以下操作解决了该问题:
DBCursor cursor = dbCollection.find(query).sort(new BasicDBObject("date", -1));
List<DBObject> arr = new ArrayList<DBObject>();
while(cursor.hasNext()){
DBObject dbo = cursor.next();
dbo.put("date", simpleDate.format(dbo.get("date")));
arr.add(dbo);
}
return JSON.serialize(arr);
Summary: I pass every DBObject from the cursor into the while loop, here I edit it with simpledateformat 摘要:我将光标中的每个DBObject传递到while循环中,在这里我使用simpledateformat对其进行编辑
simpleDate is a SimpleDateFormat("dd-MM-yyyy") object
Then, i put every item in an arraylist, which i then serialize with JSON.serialize, then i return it to my JavaScript. 然后,我将每个项目放入一个arraylist中,然后使用JSON.serialize进行序列化,然后将其返回到我的JavaScript中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.