用Java管理MongoDB嵌入式文档
我正在使用Java和MongoDB驱动程序3.10.1,在一个集合中,我需要存储带有日期的付款,所以看起来像这样用Java管理MongoDB嵌入式文档,java,arrays,mongodb,Java,Arrays,Mongodb,我正在使用Java和MongoDB驱动程序3.10.1,在一个集合中,我需要存储带有日期的付款,所以看起来像这样 "paid" : { "price" : "100", "Date" : "2019-10-06T00:00:00Z" }, 但是,我成功地插入了该文件,并使用以下查询对其进行了更新: LocalDate date = LocalDate.now(); Document payment = new D
"paid" : {
"price" : "100",
"Date" : "2019-10-06T00:00:00Z"
},
但是,我成功地插入了该文件,并使用以下查询对其进行了更新:
LocalDate date = LocalDate.now();
Document payment = new Document("price" , paid_price)
.append("Date", date);
collection.updateOne(eq("_id", new ObjectId(guest1)),
combine(set("paid",payment ),currentDate("lastModified") ));
所以,我的问题是:如何在paid中添加多个这些嵌入文档,使其看起来像下面的示例,如何使用简单的方法访问每个文档
{
"paid": [{
"price": "100",
"Date": "2019-10-06T00:00:00Z"
},
{
"price": "100",
"Date": "2019-10-06T00:00:00Z"
},
{
"price": "100",
"Date": "2019-10-06T00:00:00Z"
}
]
}
最后一个问题是:在面向对象编程中使用mongodb的最佳实践是什么?以每个类的json解析器为例??或者创建访问mongo并返回数据的方法?我希望这能有所帮助。我会这样做的
//import java.util.ArrayList;
//import org.bson.Document;
要嵌入对象,需要声明计划使用的对象。而不是通过循环初始化对象并添加它。我创建了计划添加到阵列中的三个对象
Document root= new Document();
ArrayList rootPaid= new ArrayList();
Document rootPaid0 = new Document();
Document rootPaid1 = new Document();
Document rootPaid2 = new Document();
然后在这些子对象上填充信息。您可以迭代这个过程,并根据需要添加任意多的对象。每次迭代都必须初始化文档对象,填充信息,然后添加到根目录中
rootPaid0.append("price","100");
rootPaid0.append("Date","2019-10-06T00:00:00Z");
rootPaid1.append("price","100");
rootPaid1.append("Date","2019-10-06T00:00:00Z");
rootPaid2.append("price","100");
rootPaid2.append("Date","2019-10-06T00:00:00Z");
此时,我将所有对象合并在一起以生成所需的json
if (!rootPaid.isEmpty()){
root.append("paid",rootPaid);
}
if (!rootPaid0.isEmpty()){
rootPaid.add(rootPaid0);
}
if (!rootPaid.isEmpty()){
root.append("paid",rootPaid);
}
if (!rootPaid1.isEmpty()){
rootPaid.add(rootPaid1);
}
if (!rootPaid.isEmpty()){
root.append("paid",rootPaid);
}
if (!rootPaid2.isEmpty()){
rootPaid.add(rootPaid2);
}
if (!rootPaid.isEmpty()){
root.append("paid",rootPaid);
}
乌拉!你有你的JSON
System.out.println(root.toJson());
查看
$push
操作符。您希望将新子文档推送到该paid
数组,而不是set
。