简体   繁体   English

使用 spring 数据 mongo 插入 Mongo 文档

[英]Upsert Mongo Document using spring data mongo

I have a Class我有一个班级

@Document
public class MyDocument {
   @Id
   private String id;
   private String title;
   private String description;
   private String tagLine;

   @CreatedDate
   private Date createdDate;

   @LastModifiedDate
   private Date updatedDate;

   public String getId() {
     return id;
   }
   public void setId(String id) {
     this.id = id;
   }

   public String getTitle() {
     return title;
   }

   public void setTitle(String title) {
     this.title = title;
   }

   public String getDescription() {
     return description;
   }

  public void setDescription(String description) {
    this.description = description;
  }
  public String getTagLine() {
     return tagLine;
   }

  public void setTagLine(String tagLine) {
    this.tagLine = tagLine;
  }
}

i have added annotated application with @EnableMongoAuditing我用@EnableMongoAuditing添加了带注释的应用程序

i have created interface which implements mongorepository我已经创建了实现 mongorepository 的接口

public interface MyDocumentRepository extends MongoRepository<MyDocument, String> { }

when i have created RestController with GET , POST , PATCH methods in POST I'm sending {'title':'first'}当我创建RestController用GETPOSTPATCH的方法POST我送{'title':'first'}

Controller Class POST method is控制器类 POST 方法是

@RequestMapping(value = "/", method = RequestMethod.POST)
public ResponseEntity<?> saveMyDocument(@RequestBody MyDocument myDocument) { 
   MyDocument doc = myDocumentRepo.save(myDocument);
   return new ResponseEntity<MyDocument>(doc, HttpStatus.CREATED);
}

Its saving the data in mongo.它将数据保存在 mongo 中。

{
    "_id" : ObjectId("56b3451f0364b03f3098f101"),
    "_class" : "com.wiziq.service.course.model.MyDocument",
    "title" : "test"
}

and PATCH request is like和 PATCH 请求就像

@RequestMapping(value = "/{id}", method = RequestMethod.PATCH)
public ResponseEntity<MyDocument> updateCourse(@PathVariable(value = "id") String id,
        @RequestBody MyDocument myDocument) {
    myDocument.setId(id);
    MyDocument doc = courseService.save(myDocument);
    return ResponseEntity.ok(course);
}

when in make PATCH request with data {"description":"This is test"} it update the docuent BUT it removes title field and createdDate form the document, its doing update which is ok.当使用数据{"description":"This is test"}发出 PATCH 请求时,它更新文档它从文档中删除标题字段和 createdDate,它的更新是可以的。 But i wanted to do an upsert, i can do its using mongoTemplate, but there i have to set each property which i want to set.但是我想做一个 upsert,我可以使用 mongoTemplate 来做,但是我必须设置我想要设置的每个属性。

Is there any generic way to that if i get a PATCH request i can update only not null properties.. properties which are coming in request如果我收到 PATCH 请求,是否有任何通用的方法,我只能更新非空属性.. 请求中的属性

spring-data-rest seems to do it using @RepositoryRestResource. spring-data-rest 似乎使用@RepositoryRestResource 来做到这一点。 How can i achieve the same.我怎样才能达到同样的目标。

I don't want to code like this Update update = new Update().set("title", myDocument.getTitle()).set("description", myDocument.getdescription());我不想这样编码Update update = new Update().set("title", myDocument.getTitle()).set("description", myDocument.getdescription());

Unfortunately its the behavior in MongoDB, you can verify the same using shell.不幸的是它在 MongoDB 中的行为,您可以使用 shell 验证相同的行为。 So to update create an Update Object and using所以要更新创建一个更新对象并使用

Query query = new Query(Criteria.where("id").is(ID)); 

Here ID is the document which you want to update.Based on your requirement set upsert after that using findAndModify update document.这里 ID 是您要更新的文档。根据您的要求,使用 findAndModify 更新文档后设置 upsert。

mongoTemplate.findAndModify(query, update,
                new FindAndModifyOptions().returnNew(true).upsert(false),
                someclass.class);

If you have a model like MyModel.class and you need a smooth way to create an Update object from it there is no real clear way how to do this but you can use MongoConverter bean that is created in Spring Data Mongo auto configuration and then just use replaceOne method of MongoCollection.如果你有一个像 MyModel.class 这样的模型,并且你需要一种平滑的方式来创建一个更新对象,那么没有真正明确的方法来做到这一点,但是你可以使用在 Spring Data Mongo 自动配置中创建的 MongoConverter bean,然后只是使用 MongoCollection 的 replaceOne 方法。

@Autowired
private MongoTemplate template;
@Autowired
private MongoConverter mongoConverter;

...

@Override
public void upsertMyModel(MyModel model) {
    Document documentToUpsert = new Document();
    mongoConverter.write(model, documentToUpsert);
    template.getCollection(collectionName).replaceOne(
            Filters.eq("_id", model.getId()),
            documentToUpsert,
            new ReplaceOptions().upsert(true));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM