Dear people in this group,
unfortunately, I haven't been able to find a way to query the database appropriately. Consider the following document objects:
{
"type" : "a",
"objects_with_values" : [
{ "object_id" : 0x00,
"object_type" : "A",
"object_values" : [ 0, 1, 2 ]
},
{ "object_id" : 0x01,
"object_type" : "B",
"object_values" : [ 3, 4, 6 ]
}
]
}
{
"type" : "b",
"objects_with_values" : [
{ "object_id" : 0x03,
"object_type" : "A",
"object_values" : [ 7, 8, 9 ]
},
{ "object_id" : 0x04,
"object_type" : "B",
"object_values" : [ 5, 10, 11 ]
}
]
}
I have two questions:
a) Is it possible to query via placeholders, e.g.
collection.find(document{} << "objects_with_values.$.object_type" << "A" << finalize);
If not, what would be the preferred way to find all object_values of type == b and object_type == A?
auto r{collection.find(document{} << "type" << "a" << finalize)};
auto elem{r["object_with_values"]};
// ... determine length of elem
[ { "$unwind" : "$objects_with_values", // Separate each document into one document for each element in the array in the given field }, { "$match" : { "objects_with_values.object_type" : "A", // Select only the documents with the field matching a certain value } }, { "$replaceRoot" : { "newRoot" : "$objects_with_values", // Replace each document with the specified subdocument } }])
for (auto&& document : collection.aggregate(...)) {
auto object_values = document[object_values].get_array();
std::cout << "length of array: " << std::distance(object_values.begin(), object_values.end()) << std::endl;
}
// Prints out "3{newline}3{newline}", since the two subdocuments in the example you gave both have 3 elements in their respective "object_values" subarrays.