Insert DBObject into MongoDB using Spring Data

后端 未结 3 1121
暖寄归人
暖寄归人 2021-02-15 16:11

I tried to insert the following DBObject into MongoDB using Spring Data:

    BasicDBObject document = new BasicDBObject();
    document.put(\"country\", \"us\");         


        
3条回答
  •  后悔当初
    2021-02-15 16:57

    Another way to do it

    Import statements

    import com.mongodb.client.MongoCollection;
    import org.bson.Document;
    import org.springframework.data.mongodb.core.MongoTemplate;
    

    Member Variables

      @Autowired MongoTemplate mongoTemplate;
    
      MongoCollection collection;
      @PostConstruct
      public void init(){
        collection = mongoTemplate.getCollection("company");
      }
    

    And then, the method

    public void insertRawData(){
        Document company = new Document(new HashMap()); // If you have to insert a hashMap 
    // otherwise you can add one-by-one using company.put("foo","bar")
        collection.insertOne(company);
    }
    

提交回复
热议问题