Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize MongoDB ObjectId to string

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.

like image 831
user3170702 Avatar asked Oct 30 '22 12:10

user3170702


1 Answers

Yes, sure. Use this snippet:

ObjectId objectId = new ObjectId(); // somehow got it
String stringValue = objectId.toHexString();
// And vice versa
ObjectId restoredObjectId = new ObjectId(stringValue);
like image 134
alex.b Avatar answered Nov 15 '22 05:11

alex.b