公司里使用mongoDB,一直没机会尝试。今天不是很忙,试了一下。
server端的话,下载下来就是可执行程序,直接 nohup ./mongod & 放到后台运行就ok了。
当然mongoshell也没问题。
接下来试了三种语言的client。
1 php
用pcel 安装 driver
代码:
$mo = new Mongo();
print_r($mo->listDBs());
$coll = $mo->selectCollection('mydb', 'things');
$cursor = $coll->find();
while($cursor->hasNext()){
$r = $cursor->getNext();
print_r($r);
}
2 c mongodb-mongo-c-driver-879b67c
用 scons (python的一个工具) 安装
代码:
#include <stdio.h>
#include "mongo.h"
// gcc -Isrc --std=c99 /root/down/mongodb-mongo-c-driver-879b67c/src/*.c -I /root/down/mongodb-mongo-c-driver-879b67c/src/ mongo.c -o mon
//
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_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("Connect ok.... %d\n", MONGO_OK);
}
mongo_cursor cursor[1];
mongo_cursor_init( cursor, conn, "mydb.things" );
while( mongo_cursor_next( cursor ) == MONGO_OK )
bson_print( &cursor->current );
mongo_cursor_destroy( cursor );
mongo_destroy( conn );
return 0;
}
3 perl (MongoDB-0.45)
安装时注意依赖,有Moose必须安装
代码:
#!/usr/bin/perl
use strict;
use warnings;
use MongoDB;
use Data::Dumper;
my $connection = MongoDB::Connection->new(host => 'localhost', port => 27017);
my $database = $connection->mydb;
my $collection = $database->things;
my $data = $collection->find();
while (my $obj = $data->next) {
print Dumper $obj;
}
基本能用了。
如果想深入使用高级功能,需要研究各自的API。