使用带有mongodb api的java从mongodb中检索数组

时间:2015-08-23 06:39:23

标签: java mongodb mongodb-java

据我所知,有很多问题都是一样的,而且回答得很好。问题是所有这些问题都使用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)));

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

中更新数组

这是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"
    }
]

}

4 个答案:

答案 0 :(得分:5)

To avoid unchecked casts and linter warnings, along with writing your own loop, use the libary's get(final Object key, final Class<T> clazz) method:

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

where docClazz is something that you create once:

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

答案 1 :(得分:3)

你不需要写这么多代码。请检查以下代码,

 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)));

        }
}

答案 2 :(得分:0)

这里简化了!

版本-mongo-java-driver-3.12.5.jar

comments = post.getList("comments", Document.class);

答案 3 :(得分:0)

如果你被迫使用旧版本的mongo驱动,并且你不能使用MKP提到的方法,那么你可以复制该方法本身。

这里是 Kotlin 扩展

import org.bson.Document
import java.lang.String.format

fun <T> Document.getList(key: String, clazz: Class<T>, defaultValue: List<T>): List<T> {
    val list = this.get(key, List::class.java)
    if (list == null) {
        return defaultValue
    }
    list.forEach {
        if (!clazz.isAssignableFrom(it!!::class.java)) {
            throw ClassCastException(format("List element cannot be cast to %s", clazz.getName()))
        }
    }
    return list as List<T>
}