0

In my MongoDB Java driver I retrieve some documents with a query.

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.
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("");
And this prints out "27-11-2014", just like i want it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
ErikBrandsma
  • 1,661
  • 2
  • 20
  • 46

1 Answers1

0

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

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.

ErikBrandsma
  • 1,661
  • 2
  • 20
  • 46