2

我正在尝试连接到 mongodb 并插入 GET 参数,使用 G-WAN 和 mongodb 的 C 驱动程序,我成功连接到 mongodb,但我没有成功插入任何数据。我正在使用代码

mongo_write_concern_init(write_concern);
write_concern->w = 0;
mongo_write_concern_finish(write_concern);
bson b[1];
bson_init( b );
bson_append_new_oid( b, "_id" );
bson_append_string( b, "param1", param1);
bson_append_string( b, "param2", param2);

status = mongo_insert( conn, "mydb.mycol", b , write_concern);
bson_finish( b );
bson_destroy( b );
mongo_write_concern_destroy(write_concern);

连接成功,通过 mongod.log 文件可以看到;

[conn36] run command admin.$cmd { ismaster: 1 }
[conn36] command admin.$cmd command: { ismaster: 1 } ntoreturn:1 reslen:71 0ms
[conn36] end connection 127.0.0.1:50086

但仅此而已,当我调用最后一个错误时,我也无法在 mongodb shell 上收到任何错误消息或错误日志

> db.getLastError()
null

返回 null 知道为什么会发生这种情况,或者欢迎您提出任何解决方案,谢谢

4

1 回答 1

2

此调用必须在 mongo_insert() 之前:

bson_finish( b );

否则你在这里有一个未完成的 BSON 对象:

status = mongo_insert( conn, "mydb.mycol", b , write_concern);

所以代码应该是

bson b[1];

/// Init
bson_init( b );
bson_append_new_oid( b, "_id" );
bson_append_string( b, "param1", param1);
bson_append_string( b, "param2", param2);

// Make this complete
bson_finish( b );

/// Insert
status = mongo_insert( conn, "mydb.mycol", b , write_concern);

/// Destroy the BSON obj
bson_destroy( b );
于 2012-07-13T10:32:50.733 回答