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

如何使用mongoc driver(Mongo C驱动)实现sec字段区间查询

Mongoc Driver等效查询实现

前提说明

现有MongoDB集合example_Collection,单条数据结构示例如下:

{
  "_id": ObjectId("100"),
  "source_timestamp":{
    "sec" : 90000
  }
}

需求为查询sec值满足≥9000 且 <10000的文档,原生查询语句为:

db.example_Collection.find({"source_timestamp.sec":{$gte:9000,$lt:10000}})

等效mongoc代码实现

你可以通过BCON宏快速构造BSON查询条件,完整参考代码如下:

#include <mongoc/mongoc.h>

int main (int argc, char *argv[]) {
  mongoc_client_t *client;
  mongoc_collection_t *collection;
  mongoc_cursor_t *cursor;
  const bson_t *doc;
  bson_t *query;
  char *str;

  // 初始化mongoc客户端
  mongoc_init ();
  client = mongoc_client_new ("mongodb://localhost:27017");
  collection = mongoc_client_get_collection (client, "替换为实际数据库名", "example_Collection");

  // 构造查询条件,字段路径和原生查询完全对应
  query = BCON_NEW ("source_timestamp.sec", 
                    "{", 
                      "$gte", BCON_INT32 (9000), 
                      "$lt", BCON_INT32 (10000), 
                    "}");

  // 执行查询
  cursor = mongoc_collection_find_with_opts (collection, query, NULL, NULL);

  // 遍历查询结果
  while (mongoc_cursor_next (cursor, &doc)) {
    str = bson_as_canonical_extended_json (doc, NULL);
    printf ("%s\n", str);
    bson_free (str);
  }

  // 资源释放,必须执行避免内存泄漏
  bson_destroy (query);
  mongoc_cursor_destroy (cursor);
  mongoc_collection_destroy (collection);
  mongoc_client_destroy (client);
  mongoc_cleanup ();

  return 0;
}

注意事项

  • 如果你实际业务中字段路径为source.timestamp.sec,仅需将BCON_NEW第一个参数替换为对应路径即可,逻辑和原生查询完全一致
  • 若sec字段存储的是长整型数值,可将BCON_INT32替换为BCON_INT64适配类型

内容的提问来源于stack exchange,提问作者Kavita Jain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:06:05