5

I'm connecting to MongoDB from a Spring Boot application using mongo-driver 3.2.2.

public List<Document> getNodes() {
    return mongoDatabase.getCollection("nodes").find().into(new ArrayList<Document>());
}

...

@RequestMapping("/nodes")
public List<Document> nodes(HttpServletResponse response) {
    return mongoRepository.getNodes();
}

Currently my API returns _id as objects:

"_id":{"timestamp":1486646209,"machineIdentifier":14826340,"processIdentifier":16048,"counter":2373754,"time":1486646209000,"date":1486646209000,"timeSecond":1486646209}

but I need them as hex strings. Is there any way I can manipulate the serialization to achieve this? I'm not using entity classes.

user3170702
  • 1,971
  • 8
  • 25
  • 33

1 Answers1

2

Yes, sure. Use this snippet:

ObjectId objectId = new ObjectId(); // somehow got it
String stringValue = objectId.toHexString();
// And vice versa
ObjectId restoredObjectId = new ObjectId(stringValue);
alex.b
  • 1,448
  • 19
  • 23
  • Thanks, but I need ObjectId to be always serialized to a string. I want to avoid doing it manually. – user3170702 Feb 11 '17 at 12:00
  • Not a problem. If you use Jakson (or any other) JSON serializer just create custom for that field which contains ObjectId. F.e. http://stackoverflow.com/questions/7161638/how-do-i-use-a-custom-serializer-with-jackson – alex.b Feb 11 '17 at 18:35