ILAPE
ILAPE

Reputation: 67

Straightforward way to store protobuf java object in Mongodb?

When there is a need to store protobuf3 message coming in form of Java instance (from the generated java class), the best option is to store the object itself and later to read it back from the database.

My usecase it to store such messages in Mongodb. While investigating this, I couldn't find a way, so decided to ask here.

Upvotes: 1

Views: 5188

Answers (1)

glytching
glytching

Reputation: 47935

You could transform the Protobufs Java class to JSON and from JSON to an org.bson.Document and then write the document and reverse that transform when reading.

See JsonFormat for more details.

Here's a simple example on the write side:

YourProtobufsClass anInstance = YourProtobufsClass.getDefaultInstance();

String json = JsonFormat.printer().print(yourProtobufsClass); 

Document document = Document.parse(json);

mongoClient.getDatabase(...).getCollection(...).insertOne(document);

Here's a simple example on the read side:

JsonFormat.Parser parser = JsonFormat.parser();

FindIterable<Document> documents = collection.find(...);
for (Document document : documents) {
  YourProtobufsClass.Builder builder = YourProtobufsClass.newBuilder();

  parser.merge(document.toJson(), builder);

  // now you can build an instance of your protobufs class which 
  // has been populated from the retrieved JSON
  YourProtobufsClass anInstance = builder.build();
}

Upvotes: 8

Related Questions