JSON Insert in Mongo JSON Insert in Mongo json json

JSON Insert in Mongo


I think you should not creat a JsonObject and parse it afterwards:

Can you simply try this:

    Document doc = new Document()            .append("id", UUID.randomUUID())            .append("cid", document.getCid());    mongoCollection.insertOne(doc);


I use Spring for this. The code reads as follows:

import com.mongodb.MongoClient;import org.springframework.data.mongodb.core.MongoTemplate;public class MyDao {    private final MongoTemplate template;    public MyDao(MongoClient client, String db) {        this.template = new MongoTemplate(client, db);    }    public <T extends Serializable> void store(Collection<T> data, String collectionName) {        template.insert(data, collectionName);    }}


Resolved this by using Mongo POJO Codec.

CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),                fromProviders(PojoCodecProvider.builder().automatic(true).build()));    CodecRegistry codecRegistry =                fromRegistries(CodecRegistries.fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)),                        MongoClientSettings.getDefaultCodecRegistry(),pojoCodecRegistry                );

and then you can choose to start a client with given codec or start a database with the codec registry or the collection with the codec.

Reference - https://mongodb.github.io/mongo-java-driver/3.8/driver/getting-started/quick-start-pojo/