Inserting Java Object to MongoDB Collection Using Java

后端 未结 11 1187
情话喂你
情话喂你 2020-12-28 13:34

I am trying to insert a whole Java object into a MongoDB Collection using Java. I am getting following error:

Error :

Exception in t         


        
11条回答
  •  南方客
    南方客 (楼主)
    2020-12-28 13:50

    Just use "insertOne" method, not save.

        MongoCollection collection;
        String collectionName = "somename";
        String jsonObject = "{}";
    
        if (!mongoTemplate.collectionExists(collectionName)) {
            collection = mongoTemplate.createCollection(collectionName);
            logger.info("Collection %s was successfully created", collectionName);
        } else {
            collection = mongoTemplate.getCollection(collectionName);
        }
    
        collection.insertOne(Document.parse(jsonObject));
    

提交回复
热议问题