9

カーソルを使用してドキュメントを反復処理しようとしています。それらをリストに格納し、後で DBOject タイプのリストを返します。

ここに私がしようとしているものがあります:

public List<DBObject> getResultsInDescendingOrderByDate(int limit) {

        List<DBObject> myList = null;
        DBCursor myCursor=myCollection.find().sort(new BasicDBObject("date",-1)).limit(10);
        try {
        while(myCursor.hasNext()) {

                System.out.print(myCursor.next());
               myList.add(new BasicDBObject("_id",(String) myCursor.curr().get("_id"))
                        .append("title",(String) myCursor.curr().get("title"))
                        .append("author",(String) myCursor.curr().get("author"))
                        .append("permalink",(String) myCursor.curr().get("permalink"))
                        .append("body",(String) myCursor.curr().get("body"))
                        .append("comment",new BasicDBObject("comments",(String) myCursor.curr().get("comments")))
                                .append("tags",new BasicDBObject("tags",(String) myCursor.curr().get("tags"))
                                .append("date",(Date) myCursor.curr().get("date"))));
                myCursor.next();
            }
        }

        finally {
            myCursor.close();
        }


        return myList;
    }

データ型をカーソルからプリミティブ型に変換する方法がわかりません。検索してみましたが、手がかりはありません。

助けてください。

ありがとう

4

3 に答える 3

16

@sdanzigソリューションは機能しますが...入力するコードを減らしたい場合は、これを行うことができます:

public List<DBObject> getResultsInDescendingOrderByDate(int limit) {

        List<DBObject> myList = null;
        DBCursor myCursor=myCollection.find().sort(new BasicDBObject("date",-1)).limit(10);
        myList = myCursor.toArray();

        return myList;
    }

DBCursorのDBCursor.toArray()メソッドは List を返します

于 2013-12-26T21:49:58.630 に答える
6

あなたがやろうとしていることについて、個々のフィールドを読む必要はありません。リストを初期化する必要があります。さらに、print ステートメントで 1 回、next() を 2 回呼び出していました。curr() を呼び出す代わりに、next() の戻り値を使用できます。ああ、それが意図的でない限り、10を使用するのではなく、「制限」引数を渡す必要があると誰かが正しく提案しました:

public List<DBObject> getResultsInDescendingOrderByDate(int limit) {
    List<DBObject> myList = new ArrayList<DBObject>();
    DBCursor myCursor=myCollection.find().sort(new BasicDBObject("date",-1)).limit(limit);
    try {
        while(myCursor.hasNext()) {
            myList.add(myCursor.next());
        }
    }
    finally {
        myCursor.close();
    }
    return myList;
}
于 2013-10-25T04:09:46.570 に答える