2016-11-04 1 views
1

나는 컬렉션의 문서를 반대로 표시하려고합니다. 나는 자연을 설정하는 방법Mongocxx : 문서를 반대로 표시하는 방법

void sort(bsoncxx::document::view_or_value ordering);

/// The order in which to return matching documents. If $orderby also exists in the modifiers 
/// document, the sort field takes precedence over $orderby. 
/// 
/// @param ordering 
/// Document describing the order of the documents to be returned. 
/// 
/// @see http://docs.mongodb.org/manual/reference/method/cursor.sort/ 

:이 기능을 발견 한 문서에서

db.testcollection.find().sort({$natural:-1})

: 쉘에서 이것은 다음 명령을 이용하여 수행 할 수 있습니다 쉘 예제에서 -1로? 감사!

답변

2

bsoncxx 빌더를 사용하여 정렬 순서 문서를 작성해야합니다. 다음은 10 개의 문서를 삽입하고 역순으로 덤프하는 예제입니다.

#include <iostream> 

#include <bsoncxx/builder/stream/document.hpp> 
#include <bsoncxx/document/value.hpp> 
#include <bsoncxx/document/view.hpp> 
#include <bsoncxx/json.hpp> 
#include <mongocxx/client.hpp> 
#include <mongocxx/collection.hpp> 
#include <mongocxx/instance.hpp> 
#include <mongocxx/options/find.hpp> 
#include <mongocxx/uri.hpp> 

using namespace bsoncxx; 

int main() { 
    auto inst = mongocxx::instance{}; 
    auto client = mongocxx::client{mongocxx::uri{}}; 
    auto coll = client["test"]["sorttest"]; 
    coll.drop(); 

    for (auto i = 0; i < 10; i++) { 
     coll.insert_one(builder::stream::document{} << "seq" << i << builder::stream::finalize); 
    } 

    auto order = builder::stream::document{} << "$natural" << -1 << builder::stream::finalize; 

    auto opts = mongocxx::options::find{}; 
    opts.sort(order.view()); 

    auto cursor = coll.find({}, opts); 

    for (auto&& doc : cursor) { 
     std::cout << to_json(doc) << std::endl; 
    } 
} 
+0

대단히 고마워요! – zerocool