簡體   English   中英

使用java和mongodb api從mongodb檢索數組

[英]retrieve array from mongodb using java with mongodb api

我知道有很多相同的問題,並且得到了很好的回答。 問題是所有這些問題都使用 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數組本身中創建另一個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"
    }
]

}

為了避免未經檢查的強制轉換和 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();

您無需編寫這么多代碼。 請檢查以下代碼,

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

        }
}

這在這里簡化了很多!

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

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

如果您被迫使用舊版本的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>
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM