|
1 | 1 | #include "catch.hpp" |
2 | 2 |
|
| 3 | +#include <vector> |
| 4 | + |
3 | 5 | #include <bsoncxx/builder/stream/document.hpp> |
| 6 | +#include <bsoncxx/json.hpp> |
| 7 | +#include <bsoncxx/stdx/string_view.hpp> |
4 | 8 | #include <bsoncxx/types.hpp> |
| 9 | + |
5 | 10 | #include <mongocxx/collection.hpp> |
6 | 11 | #include <mongocxx/client.hpp> |
7 | 12 | #include <mongocxx/pipeline.hpp> |
@@ -388,4 +393,57 @@ TEST_CASE("CRUD functionality", "[driver::collection]") { |
388 | 393 |
|
389 | 394 | auto results = coll.aggregate(p); |
390 | 395 | } |
| 396 | + |
| 397 | + SECTION("distinct works", "[collection]") { |
| 398 | + using bsoncxx::builder::stream::document; |
| 399 | + |
| 400 | + auto distinct_cname = "distinct_coll"; |
| 401 | + auto distinct_coll = db[distinct_cname]; |
| 402 | + if (db.has_collection(distinct_cname)) { |
| 403 | + distinct_coll.drop(); |
| 404 | + } |
| 405 | + |
| 406 | + document doc1{}; |
| 407 | + doc1 << "foo" << "baz" << "garply" << 1; |
| 408 | + document doc2{}; |
| 409 | + doc2 << "foo" << "bar" << "garply" << 2; |
| 410 | + document doc3{}; |
| 411 | + doc3 << "foo" << "baz" << "garply" << 2; |
| 412 | + document doc4{}; |
| 413 | + doc4 << "foo" << "quux" << "garply" << 9; |
| 414 | + |
| 415 | + bulk_write bulk{false /* unordered */}; |
| 416 | + |
| 417 | + bulk.append(model::insert_one{doc1}); |
| 418 | + bulk.append(model::insert_one{doc2}); |
| 419 | + bulk.append(model::insert_one{doc3}); |
| 420 | + bulk.append(model::insert_one{doc4}); |
| 421 | + |
| 422 | + distinct_coll.bulk_write(bulk); |
| 423 | + |
| 424 | + auto distinct_results = distinct_coll.distinct("foo", {}); |
| 425 | + |
| 426 | + // copy into a vector. |
| 427 | + std::vector<bsoncxx::document::value> results(distinct_results.begin(), |
| 428 | + distinct_results.end()); |
| 429 | + REQUIRE(results.size() == std::size_t{1}); |
| 430 | + |
| 431 | + auto res_doc = results[0].view(); |
| 432 | + |
| 433 | + auto values_array = res_doc["values"].get_array().value; |
| 434 | + |
| 435 | + std::vector<bsoncxx::stdx::string_view> distinct_values; |
| 436 | + for (auto&& value : values_array) { |
| 437 | + distinct_values.push_back(value.get_utf8().value); |
| 438 | + } |
| 439 | + |
| 440 | + const auto assert_contains_one = [&](bsoncxx::stdx::string_view val) { |
| 441 | + REQUIRE(std::count(distinct_values.begin(), distinct_values.end(), val) == 1); |
| 442 | + }; |
| 443 | + |
| 444 | + assert_contains_one("baz"); |
| 445 | + assert_contains_one("bar"); |
| 446 | + assert_contains_one("quux"); |
| 447 | + } |
| 448 | + |
391 | 449 | } |
0 commit comments