gpt4 book ai didi

java - 使用java和mongodb api从mongodb检索数组

转载 作者:可可西里 更新时间:2023-11-01 09:20:44 24 4
gpt4 key购买 nike

我知道有很多问题都是一样的,而且回答得很好。问题是所有这些问题都使用 MongoDBObject、MongoDBList 来检索数组。我的问题是我正在使用 http://api.mongodb.org/java/3.0/index.html?overview-summary.html api,我很难检索数组并向其添加元素。我必须使用 MongoCollection、MongoDatabase 和 MongoClient。我正在尝试解决 mongodb 类(class)的作业。问题陈述是找到一个数组并在 mongod 中更新它。

这是我尝试过的

      Document post = null; Bson filter = new Document("permalink",
permalink); Bson projection = new Document("comments", true);
List<Document> comments = postsCollection.find(filter)
.projection(projection).into(new ArrayList<Document>());
System.out.println(comments);

post = postsCollection.find(Filters.eq("permalink",
permalink)).first();

Document newComment = new Document();

newComment.append("author", name); newComment.append("body", body);
if (email != null && (!email.equals(""))) {
newComment.append("email", email); }

comments.add(newComment);

Bson filter2 = new Document("_id", post.get("_id"));
System.out.println(comments); post =
postsCollection.find(filter).first();

postsCollection.updateOne(filter2, new Document("$unset",new
Document("comments",true))); postsCollection.updateOne(filter2, new
Document("$set", new Document( "comments", comments)));

这不会创建新评论。相反,它会在 comments 数组本身中创建另一个 comments 数组。数组应该在 student

中更新

这里是json数据

{
"_id" : ObjectId("55d965eee60dd20c14e8573e"),
"title" : "test title",
"author" : "prasad",
"body" : "test body",
"permalink" : "test_title",
"tags" : [
"test",
"teat"
],
"date" : ISODate("2015-08-23T06:19:26.826Z"),
"comments" : [
{
"_id" : ObjectId("55d965eee60dd20c14e8573e"),
"comments" : [
{
"_id" : ObjectId("55d965eee60dd20c14e8573e"),
"comments" : []
},
{
"author" : "commented",
"body" : "something in comment",
"email" : "some@thing.com"
}
]
},
{
"author" : "commented",
"body" : "something in comment",
"email" : "some@thing.com"
}
]

最佳答案

为了避免未经检查的转换和 linter 警告,以及编写您自己的循环,请使用库的 get(final Object key, final Class<T> clazz)方法:

List<Document> comments = posts.get("comments", docClazz)

哪里docClazz是你创建一次的东西:

final static Class<? extends List> docClazz = new ArrayList<Document>().getClass();

关于java - 使用java和mongodb api从mongodb检索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32163919/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com