在我的MongoDB Java驱动程序中,我使用查询检索一些文档。
DBCursor cursor = dbCollection.find(query).sort(new BasicDBObject("date", -1));
return JSON.serialize(cursor);
这样可以正常返回以下内容:
{
"isSuccessful": true,
"result": [
{
"date": {
"$date": "2014-11-26T23:00:00.000Z"
},
value: 20
}
]
}
但是:我想使用
编辑字段$ dateSimpleDateFormat
我试过这个:
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);
但是while循环不会影响返回的结果 它只是给出了相同的结果。如何更改日期字段然后返回? 我还提出以下一行:
simpleDate.format(dbo.get("date"))
在System.out.printline(“”)中;
这打印出“27-11-2014”,就像我想要的那样。
答案 0 :(得分:0)
我通过以下方式解决了这个问题:
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);
总结:我将每个DBObject从游标传递到while循环,这里我用simpledateformat编辑它
simpleDate is a SimpleDateFormat("dd-MM-yyyy") object
然后,我将每个项目放在一个arraylist中,然后我用JSON.serialize序列化,然后我将它返回到我的JavaScript。