You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB C++驱动如何查询文档子元素并遍历所有parts?

How to Retrieve All Sub-Elements of "parts" with MongoDB C++ Driver

Hey there! Let's work through this problem together. First, I need to flag a critical detail about your sample JSON structure: MongoDB (and JSON in general) doesn’t allow duplicate keys in the same document level. If you tried inserting { docID : "123", parts : { part : "a", part : "b", part : "c" } }, only the last part value ("c") would actually be stored—each subsequent "part" key overwrites the previous one.

To store multiple parts correctly, you’ll want to use an array instead. Your document should look like one of these two valid structures:

Valid Structure 1: Array of documents (each with a "part" key)

{ "docID": "123", "parts": [ { "part": "a" }, { "part": "b" }, { "part": "c" } ] }

Valid Structure 2: Array of strings (simpler, if you only need the part values)

{ "docID": "123", "parts": ["a", "b", "c"] }

With that sorted, here’s how to retrieve all parts from your existing document reference:

Code Implementation

// First, check if the document was found (always good practice!)
if (resultDocument) {
    bsoncxx::document::view viewDocumentResult = resultDocument.value();

    // Verify the "parts" field exists and is an array
    if (viewDocumentResult["parts"] && viewDocumentResult["parts"].type() == bsoncxx::type::k_array) {
        auto parts_array = viewDocumentResult["parts"].get_array().value;

        // Iterate over each element in the array
        for (const auto& element : parts_array) {
            // Handle Structure 1: Array of documents with "part" key
            if (element.type() == bsoncxx::type::k_document) {
                auto part_doc = element.get_document().value;
                if (part_doc["part"] && part_doc["part"].type() == bsoncxx::type::k_string) {
                    std::string part_value = part_doc["part"].get_string().value.to_string();
                    std::cout << "Part: " << part_value << std::endl;
                }
            }
            // Handle Structure 2: Array of strings
            else if (element.type() == bsoncxx::type::k_string) {
                std::string part_value = element.get_string().value.to_string();
                std::cout << "Part: " << part_value << std::endl;
            }
        }
    } else {
        std::cerr << "Error: 'parts' field is missing or not an array!" << std::endl;
    }
} else {
    std::cerr << "Error: Document with docID '123' not found in the collection!" << std::endl;
}

Key Notes:

  • Null Safety: We add checks for the existence of fields and their correct types to avoid runtime crashes (e.g., if "parts" is missing or isn’t an array).
  • Flexibility: The code handles both common valid structures for storing multiple parts—adjust it based on your actual document schema.
  • Why Arrays?: Arrays are the standard way to store ordered lists of items in MongoDB, which aligns perfectly with your goal of retrieving all part values.

内容的提问来源于stack exchange,提问作者Fabi Held

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:39:27