Inserting Java Object to MongoDB Collection Using Java

后端 未结 11 1291
情话喂你
情话喂你 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:52

    Highly recommend MongoJack, a decent library to map Java objects to/from MongoDB documents.

    The code would be something like below:

    import java.util.Arrays;
    import org.mongojack.JacksonDBCollection;
    import com.mongodb.DB;
    import com.mongodb.MongoClient;
    import com.mongodb.ServerAddress;
    
    public class Test {
    
        public static void main(String[] args) {
    
            MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017)));
            DB db = mongoClient.getDB("test");
    
            Employee employee = new Employee();
            employee.setNo(1L);
            employee.setName("yogesh");
    
            JacksonDBCollection collectionData = JacksonDBCollection.wrap(db.getCollection("NameColl"), Employee.class, String.class);
            collectionData.save(employee);
            mongoClient.close();
        }
    
    }
    

    (PS: Currently I'm using mongo-java-driver v3.2.2, and mongojack v2.6.1)

提交回复
热议问题