Complex query with two $OrderBy

北城余情 提交于 2019-12-24 20:47:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!