使用带有mongodb api的java从mongodb中检索数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用带有mongodb api的java从mongodb中检索数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2388字,纯文字阅读大概需要4分钟。
内容图文
我知道有很多问题,并且答案很好.问题是所有这些问题都使用MongoDBObject,MongoDBList来检索数组.我的问题是我使用http://api.mongodb.org/java/3.0/index.html?overview-summary.html api,我很难检索数组并添加元素.我必须使用MongoCollection,MongoDatabase和MongoClient.我正试图解决mongodb课程的作业.问题陈述是找到一个数组并在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数组本身中创建了另一个注释数组.数组应该在学生中更新
这是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"
}
]
}
解决方法:
你不需要写这么多代码.请检查以下代码,
public void addPostComment(final String name, final String email, final String body,
final String permalink) {
Document post = findByPermalink(permalink);
List<Document> comments = null;
Document comment = new Document();
if(post != null){
comments = (List<Document>)post.get("comments");
comment.append("author",name).append("body", body);
if(email != null){
comment.append("email", email);
}
comments.add(comment);
postsCollection.updateOne(new Document("permalink",permalink),
new Document("$set",new Document("comments",comments)));
}
}
内容总结
以上是互联网集市为您收集整理的使用带有mongodb api的java从mongodb中检索数组全部内容,希望文章能够帮你解决使用带有mongodb api的java从mongodb中检索数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。