繁体   English   中英

Mongocxx:如何反向显示文档

[英]Mongocxx: How to display the documents inversely

我正在尝试反向显示集合的文档。 在外壳中,可以通过使用以下命令来完成此操作:

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

在文档中,我发现了此功能:

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/

我如何像shell示例中那样将自然值设置为-1? 谢谢!

您需要使用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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM