如何在 Spring Boot 中将 ObjectId 转换为字符串

时间:2021-01-15 10:40:48

标签: java spring-boot aggregation

我在单个 MongoDB 数据库中有 2 个集合。

demo1 collection_data:

{ 
    "_id" : ObjectId("5ff006f74a8eb25a7869aa53"), 
    "userName" : "username", 
    "password" : "password", 
    "productName" : "p3", 
    "age" : "50" 
},
{ 
    "_id" : ObjectId("5ff007664a8eb25a7869aa7c"), 
    "userName" : "user", 
    "password" : "pass", 
    "productName" : "p1", 
    "age" : "18"
}

demo2 collection_data:

{ 
    "_id" : ObjectId("5ff7f90ddd338c435e0f2b91"), 
    "userName" : "user20", 
    "password" : "pass20", 
    "email" : "user@gmail.com", 
    "age" : "15", 
    "_class" : "com.example.product.model.Demo2"
}
{ 
    "_id" : ObjectId("5ff7ff1cf91eb60ed84ba082"), 
    "userName" : "userName", 
    "password" : "password", 
    "email" : "user@gmail.com", 
    "age" : "20", 
    "_class" : "com.example.product.model.Demo2"
}

Demo1.java:-

@Document(collection = "demo1")
public class Demo1{

    @Id
    private ObjectId id;

    @NotBlank(message = "username required")
    private String productName;

    @Pattern(regexp = "([0-9]*+.[0-9]*||[0-9]*||[0-9]$)")
    private String price;

    private String age;

Demo2.java

@Document(collection = "demo2")
public class Demo2{

    @Id
    private ObjectId id;
    private String userName;
    private String password;
    private String email;
    private String age;
    private String demo1ID;//it will store converted value od objectId to string of Demo1.class. 

我想将 demo1 的所有 ObjectId 转换为 String,然后这些 String 将作为 demo1ID 存储到 demo2 集合中。我如何在 Spring Boot 中使用聚合进行这些转换并保存到 Demo2 集合中?请帮我解决这些问题。

0 个答案:

没有答案
相关问题