---
title: "mongodb c driver"
author: "kimmking"
date: "2012-03-04T22:02:56Z"
tags: []
categories: ["数据库"]
slug: "mongodb-c-driver"
draft: false
lastmod: "2012-03-04T22:02:56Z"
id: 1439808
url: "https://setting.iteye.com/blog/1439808"
---

mongodb的c driver，源码在

 

一、编译

[http://api.mongodb.org/c/current/building.html](http://api.mongodb.org/c/current/building.html)

linux、mac、windows-cygwin下，下载scons，

[http://www.scons.org/](http://www.scons.org/)，使用python setup.py install安装scons，

然后去mongodb驱动源码下，scons安装驱动，即可。

比如windows下自动生成bson.dll和mongoc.dll。

 

二、例子

 

API详细信息

[http://api.mongodb.org/c/current/api/annotated.html](http://api.mongodb.org/c/current/api/annotated.html)

 

简单的例子

[http://api.mongodb.org/c/current/tutorial.html](http://api.mongodb.org/c/current/tutorial.html)

Connecting这一节的例子有点问题：

1、status没有定义类型，

2、MONGO\_CONN\_BAD\_ARG这个常量已经在新版本里去掉了，

例子可以改为：

```
#include <stdio.h>
#include "mongo.h"

int main() {
  mongo conn[1];
  int status;
  status = mongo_connect( conn, "127.0.0.1", 27017 );

  if( status != MONGO_OK ) {
      switch ( conn->err ) {
        case MONGO_CONN_SUCCESS:    printf( "connection succeeded\n" ); break;
        //case MONGO_CONN_BAD_ARG:    printf( "bad arguments\n" ); return 1;
        case MONGO_CONN_NO_SOCKET:  printf( "no socket\n" ); return 1;
        case MONGO_CONN_FAIL:       printf( "connection failed\n" ); return 1;
        case MONGO_CONN_NOT_MASTER: printf( "not master\n" ); return 1;
      }
  }else{
  	  printf( "MONGO_OK:connection succeeded\n%d\n", status );
  }
  
  mongo_destroy( conn );

  return 0;
}

```