前言
本文章以储存期货TICK数据为例,编程软件vs2022,操作系统win10 x64。
vs2022配置
mongoc配置教程

内容
本文实现的插入数据图
在这里插入图片描述
代码实现

#include <bson/bson.h>
#include <mongoc/mongoc.h>
#include <stdio.h>


int main(int   argc,
    char* argv[])
{
    mongoc_client_t* client;
    mongoc_collection_t* collection;
    bson_error_t error;
    bson_oid_t oid;
    bson_t* doc;
    bson_t child;
    struct tm tick = { 0 };
    tick.tm_year = 99;  /* years are 1900-based */
    tick.tm_mon = 11;  /* months are 0-based */
    tick.tm_mday = 7;
    tick.tm_hour = 18;
    tick.tm_min = 55;
    tick.tm_sec = 56;
    int minec = 500;
    bson_t* command;
   // bson_t reply;
    mongoc_database_t* database1;
    

    mongoc_init();

   

    client = mongoc_client_new("mongodb://localhost:27017");
   
   database1= mongoc_client_get_database(client, "myfu");
   command = BCON_NEW("timeseries", "{", "timeField", "datetime", "}");
   collection =mongoc_database_create_collection(database1, "fu8", command,  &error);
   if (collection == NULL)
   {
       collection = mongoc_client_get_collection(client, "myfu", "fu8");
   }
       
    
    
    
  

    doc = bson_new();
   
   
   
   bson_oid_init(&oid, NULL);
    BSON_APPEND_OID(doc, "_id", &oid);
    BSON_APPEND_UTF8(doc, "ID", "SHFE");
    BSON_APPEND_UTF8(doc, "period", "tick");
    BSON_APPEND_DATE_TIME(doc, "datetime", mktime(&tick) * 1000 + 500);

    
    BSON_APPEND_DOUBLE(doc, "lastPrice", 3328.2);
    BSON_APPEND_DOUBLE(doc, "vol", 23.4);
    
   
    

    if (!mongoc_collection_insert_one(
        collection, doc, NULL, NULL, &error)) {
        fprintf(stderr, "%s\n", error.message);
    }
//释放接口

     bson_destroy(doc);
    mongoc_collection_destroy(collection);
    mongoc_client_destroy(client);
    mongoc_cleanup();

    return 0;
}

代码讲解

mongoc_init(); 这是mongoc接口的初始化函数,在主程序的最开头调用。

bson_destroy(doc);文档接口释放函数,在调用完文档后需要释放接口。

mongoc_collection_destroy(collection);mongodb集合接口释放函数,在调用完集合后需释放接口。

mongoc_client_destroy(client);mongodb服务器释放函数,在不需要连接服务器时需要释放接口。

client = mongoc_client_new("mongodb://localhost:27017");创建服务器连接。

database1= mongoc_client_get_database(client, "myfu");创建数据库。

command = BCON_NEW("timeseries", "{", "timeField", "datetime", "}");创建一个命令,该命令是创建一个mongodb时序数据集合。

collection =mongoc_database_create_collection(database1, "fu8", command, &error);带命令创建一个集合,此处是创建时序集合。

此段代码为创建需要插入数据库的时序数据

   doc = bson_new();
 
    bson_oid_init(&oid, NULL);
    BSON_APPEND_OID(doc, "_id", &oid);
    BSON_APPEND_UTF8(doc, "ID", "SHFE");
    BSON_APPEND_UTF8(doc, "period", "tick");
    BSON_APPEND_DATE_TIME(doc, "datetime", mktime(&tick) * 1000 + 500);
    BSON_APPEND_DOUBLE(doc, "lastPrice", 3328.2);
    BSON_APPEND_DOUBLE(doc, "vol", 23.4);

插入doc文档保存的时序数据

if (!mongoc_collection_insert_one(
        collection, doc, NULL, NULL, &error)) {
        fprintf(stderr, "%s\n", error.message);
    }

说明
本文为c/c++操作mongodb数据库的基本插入操作,读者可以根据自己需要的数据结构,插入自己想要的数据。
下图为作者通过期货接口实时插入mongodb数据库的期货TICK实时数据,可供读者参考。
期货tick实时数据
在这里插入图片描述

更多推荐