gpt4 book ai didi

c++ - Mongocxx : How to display the documents inversely

转载 作者:搜寻专家 更新时间:2023-10-30 21:56:48 28 4
gpt4 key购买 nike

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

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

在文档中我找到了这个函数:

无效排序(bsoncxx::document::view_or_value 排序);

/// 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 示例中那样将 natural 设置为 -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;
}
}

关于c++ - Mongocxx : How to display the documents inversely,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40423815/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com