带有两个$ OrderBy的复杂查询

时间:2014-01-24 12:36:00

标签: mongodb bson mongodb-c

这是我的收藏的结构部分:

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
   }
]

我可以按时间顺序按照时间顺序通过以下行恢复我的数据:

...
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);
   }
   ...
}
...

但是现在我想按时间顺序(或不是)检索数组“邮件”中的所有值...你对这个程序有所了解吗?

1 个答案:

答案 0 :(得分:0)

看起来您必须使用Aggregation Framework来实现这一目标。

这个想法(在javascript中):

db.test.aggregate([
    { $unwind: "$mails" }, 
    { $sort: { timestamp: 1, "mails.timestamp": 1 } }, 
    { $group: { _id: "$_id", mails: { $push: "$mails" } } }
]);

目前我不确定如何将其翻译为C.尝试查看mongoc_collection_aggregate文档。

相关问题