Insert DBObject into MongoDB using Spring Data

后端 未结 3 1131
暖寄归人
暖寄归人 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<Document> 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);
    }
    
    0 讨论(0)
  • 2021-02-15 16:58

    Another way to do this is to directly access the DBCollection object via the MongoTemplate:

    DBObject company = new BasicDBObject();
    ...
    DBCollection collection = mongoTemplate.getCollection("company");
    collection.insert(company);
    
    0 讨论(0)
  • 2021-02-15 17:06

    You are confusing spring-data with normal mongo persistence using the java driver.

    If you want to persist data to mongoDB directly using the java driver then you would use the BasicDBObject like you have shown except that you would not use the mongoTemaplate class to persist but rather the MongoClient class. So it would look like this:

    MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
    DB db = mongoClient.getDB( "mydb" );
    BasicDBObject o = new BasicDBObject();
    o.set......
    coll.insert(o);
    

    But if you are trying to persist a document using spring-data, then you need to create a java class to represent your document (eg: Person) and annotate this class with @Document(collection="person") and then use the mongoTemplate (which is a spring-data specific class to persist this entity. This is very similar to using JPA/hibernate.

    So it would look something like this

    @Document(collection="person")
    public class Person {
        private String fisrtName;
        ....
    
        Relevant getters and setters
    
    }
    

    And then the persistence

    Person p = new Person();
    p.setFirstName("foo");
    p.setLastName("bar");
    ....
    mongoTemplate.save(p);
    
    0 讨论(0)
提交回复
热议问题