问题
Here's the structure part of my collection :
by: [
{
id: ObjectId("XX"),
type: NumberInt(1)
}
],
timestamp: NumberInt(), // is timestamp 1
status: NumberInt(0),
mails: [
{
id: ObjectId("YY"),
text: "",
timestamp: NumberInt(), // is timestamp 2
}
]
I can recover my data in chronological order according to the timestamp 1 via the following lines:
...
bson_init(&query);
bson_append_document_begin(&query, "$orderby", -1, &child);
bson_append_int32(&child, "timestamp", -1, 1);
bson_append_document_end(&query, &child);
bson_append_document_begin(&query, "$query", -1, &child);
bson_append_document_end(&query, &child);
collection = mongoc_client_get_collection(client, "db", "prefix");
cursor = mongoc_collection_find(collection, MONGOC_QUERY_NONE, 0, 0, 0, &query, NULL, NULL);
while(mongoc_cursor_next(cursor, &doc)){
bson_iter_t iter;
if(bson_iter_init_find(&iter, doc, "status")){
status = bson_iter_int32(&iter);
}
...
}
...
But now I would like to retrieve all values in the array "mails" in chronological order (or not) ... Have you an idea of the procedure?
回答1:
Looks like you have to use Aggregation Framework to get this working.
The idea (in javascript):
db.test.aggregate([
{ $unwind: "$mails" },
{ $sort: { timestamp: 1, "mails.timestamp": 1 } },
{ $group: { _id: "$_id", mails: { $push: "$mails" } } }
]);
I am not sure how to translate it to C at the moment. Try to check out mongoc_collection_aggregate docs.
来源:https://stackoverflow.com/questions/21332895/complex-query-with-two-orderby