我正在尝试在mongoDB文档中现有数组的末尾添加一个字符串。
我尝试查看mongoDB的文档,这些文档将我带到push页和其他similar questions页面。到目前为止,它们都没有起作用,因为我没有我制作的ID,随着数组中新元素的添加,它们会自动生成。
收藏中的文档:
_id: 5ce85c1e1c9d4400003dcfd9
name: "Halloween party"
category: 2
date: 2019-10-31T23:00:00.000+00:00
address: "Sample Street, london"
description: "It's Halloween, bring your costumes and your personality to the studen..."
bookings: Array
0: "1610512"
我可以使用以下代码获取要在其中附加字符串的文档。
Java代码:
MongoDatabase database = mongoClient.getDatabase("KioskDB");
MongoCollection<Document> Kiosk = database.getCollection("Events");
Document searchQuery = new Document();
searchQuery.put("name", selectedActivityName);
searchQuery.put("bookings", username);
FindIterable<Document> documents = Kiosk.find(searchQuery);
for (Document document: documents){
System.out.println(document);
}
给我下面的输出
Document{{_id=5ce85c1e1c9d4400003dcfd9, name=Halloween party, category=2, date=Thu Oct 31 23:00:00 GMT 2019, address=Sample Street, london, description=It's Halloween, bring your costumes and your personality to the student Bar and join us in this age long celebration., bookings=[1610512]}}
如何在数组末尾附加一个新字符串,使我得到如下所示的内容。
所需的最终文档
_id: 5ce85c1e1c9d4400003dcfd9
name: "Halloween party"
category: 2
date: 2019-10-31T23:00:00.000+00:00
address: "Sample Street, London"
description: "It's Halloween, bring your costumes and your personality to the studen..."
bookings: Array
0: "1610512"
1: "1859301"
编辑: 可以使用以下代码找到答案。
DBObject listItem = new BasicDBObject("bookings", username);
Kiosk.updateOne(eq("name", selectedActivityName), new Document().append("$push", listItem));
其中username是数字(例如:1859301),selectedActivityName是名称字段的名称(例如:Halloween party),Kiosk是集合名称。
答案 0 :(得分:1)
我将根据文档尝试此代码。参考https://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/
Document doc = new Document("name", "Halloween party")
.append("bookings", Arrays.asList("1859301"));
答案 1 :(得分:0)
自从3.0版Java驱动程序以来,他们为过滤器添加了辅助方法,这些方法使mongo的查询变得更好,更易读。在3.1中,他们还添加了用于更新的帮助程序方法,这些方法使诸如此类的事情变得非常简单易懂,请参见:
https://mongodb.github.io/mongo-java-driver/3.6/javadoc/com/mongodb/client/model/Filters.html https://mongodb.github.io/mongo-java-driver/3.6/javadoc/com/mongodb/client/model/Updates.html
Bson query = Filters.eq("name", selectedActivityName);
Bson update = Updates.push("bookings", username);
collection.findOneAndUpdate(query, update);
也可以在旧版本中执行此操作。对于3.0之前的版本,此语法仍然适用。但是,如果您运行的版本低于3.0,则需要用BasicDBObject替换Document。
Bson query = new Document("name", selectedActivityName);
Bson update = new Document("$push", new Document("bookings", username));
collection.findOneAndUpdate(query, update);