1. 程式人生 > >MongoDb(一) -- Ubuntu Server、Windows C++ driver 連線測試

MongoDb(一) -- Ubuntu Server、Windows C++ driver 連線測試

最近在學習非關係型資料庫,先拿MongoDB開刀,準備在ubuntu上安裝服務端,windows上安裝客戶端,整合到MFC中,做一個簡單的專案練練手。但是看了很多網上的配置教程,也沒有一個能完整地配置成功。在環境搭建上耽誤了好幾天,走了不少彎路。把整個流程記錄一下,以後再次遇到問題時可以參考,也希望可以幫到有需要的同學。

關鍵字:MongoDB Ubuntu C++ driver

1. 簡介

關於MongoDB的簡介網上有很多,這裡不再贅述。這裡只總結一下MongoDB特點:

  • 面向集合儲存。

  • 沒有行列概念。文件可以有不同的key,key資料型別可以不同。

  • 查詢指令可以使用JSON。

  • 支援索引、故障恢復。

  • 使用二進位制儲存資料。

  • 檔案儲存格式為BSON。

接下來就進入整個安裝配置流程

2. Ubuntu mongoDB Server安裝

我用的Ubuntu版本是16.04,,安裝MongoDB非常簡單,使用apt-get兩條語句搞定

apt-get update
apt-get install mongodb

安裝完成後,路徑/etc/mongodb.conf 為MongoDB的配置檔案,可以配置繫結IP、埠號等配置資訊,稍後的C++驅動連線會修改這個檔案。通過ps檢視mongod後臺服務是否開啟。

[email protected]
:~$ ps aux | grep mongo mongodb 3994 0.4 0.7 639596 16044 ? Ssl 16:51 0:04 /usr/bin/mongod --config /etc/mongodb.conf pangdx 4143 0.0 0.0 13592 944 pts/1 S+ 17:06 0:00 grep --color=auto mongo

如果沒有,需要手動開啟mongod服務,手動開啟有兩種方式:

通過配置檔案啟動,這種請方式需要在配置檔案中配置啟動引數。

/usr/bin/mongod --config /etc/mongod.conf

手動直接啟動,其實就是把引數寫到了命令列裡,分別設定了資料庫路徑、後臺執行、日誌路徑。

mongod --dbpath=/usr/local/mongodb/data --fork --logpath=/usr/local/mongodb/logs

啟動mongod守護程序後,即能登入資料庫進行操作了:

[email protected]:~$ mongo
MongoDB shell version: 2.6.10
connecting to: test
> show dbs
admin  (empty)
local  0.078GB
> db.test.insert({id:1, name:'zhangsan', pos:'manager', age:'30'})
WriteResult({ "nInserted" : 1 })
> show dbs
admin  (empty)
local  0.078GB
test   0.078GB
> db.test.find()
{ "_id" : ObjectId("5b9b7721c340f92def988ae5"), "id" : 1, "name" : "zhangsan", "pos" : "manager", "age" : "30" }

3. Windows C++ driver 安裝

接下來進行Windows C++ 驅動的安裝,我的安裝環境是基於VS2010的。

如果沒有安裝過Python的同學首先需要安裝Python,因為在編譯驅動原始檔時候用到的構建工具Scons是基於Python的。如果在使用Scons構建的時候出現語法錯誤,請嘗試切換Python的版本到2.x,我這裡用的版本是2.7。

  • 下載安裝Boost庫

同樣的傻瓜式安裝。這裡需要注意的是,到底是下載32位還是64的問題,取決於在VS環境下編譯工程的配置,如果編譯32位Windows程式,則下載32位Boost,反之亦然。我下載的版本是 boost_1_60_0-msvc-10.0-32.exe。安裝完成後記下路徑,這裡有工程需要的.h、.lib和.dll檔案。

  • 下載安裝Scons

解壓後進入原始碼目錄,執行

python setup.py install

程式自動進行安裝。安裝完成後可以在cmd視窗下執行

scons --version

檢視是否安裝成功。

Microsoft Windows [版本 6.1.7601]
版權所有 (c) 2009 Microsoft Corporation。保留所有權利。

C:\Users\Administrator>scons --version
SCons by Steven Knight et al.:
        script: v2.5.0.rel_2.5.0:3544:95d356f188a3[MODIFIED], 2016/04/09 14:38:50, by bdbaddog on ubuntu1404-32bit
        engine: v2.5.0.rel_2.5.0:3544:95d356f188a3[MODIFIED], 2016/04/09 14:38:50, by bdbaddog on ubuntu1404-32bit
        engine path: ['C:\\Python27\\Scripts\\..\\Lib\\site-packages\\scons-2.5.0\\SCons']
Copyright (c) 2001 - 2016 The SCons Foundation

C:\Users\Administrator>
  • 下載編譯MongoDB C++驅動 

先說明目的:編譯驅動的目的是為了獲取工程需要的依賴檔案。如果編譯成功,會得到對應的標頭檔案和庫檔案。

C++驅動本次選用的mongo-cxx-driver-legacy-1.1.2.tar.gz版本。新版本需要通過CMake編譯原始碼,具體編譯方法可見官方網站。legacy版本原始碼通過Scons編譯,操作簡便。關於legacy版本的C++驅動,這裡引用一段官方說明。所以想嘗試新版本的同學,仍需要採用CMake構建編譯原始碼。

NOTE: The Legacy C++ driver has reached End-Of-Life. Please upgrade to the mongocxx driver.

The 26compat release series tracks the server 2.6 releases one-to-one. As a result, it receives only bugfixes and small updates necessary to keep it building in isolation.

The legacy release series, on the other hand, is a permanent and diverging fork. Our philosophy is to keep the legacy branch as close to the 26compat branch as is reasonable, but that when weighing new features against compatibility, we will choose new features. As a result the legacy branch is not 100% source compatible with the 26compat branch.

This page attempts to serve as a transition guide for those users looking to migrate from the 26compat branch to the legacy branch. Note that it does not discuss new features in detail and simply points to the per-release notes.

下載完成後,進入原始碼根目錄,如果發現含有SConstruct檔案,那麼該原始碼是可以通過scons構建的。

執行

scons install --cpppath=D:\boost_1_60_0 --libpath=D:\boost_1_60_0\lib32-msvc-10.0  --dbg=on --32 --dynamic-windows --sharedclient 

其中cpppath代表boost的安裝路徑,libpath代表boost lib庫的路徑,dbg表示編譯為debug而不是release版本。

編譯完成後會在根目錄出現build資料夾,/install路徑下存有我們需要的標頭檔案和lib庫。

這裡需要注意引數中的32位/64位需要與Boost版本匹配。如果期間更換過Boost的版本,則需要重新編譯C++驅動原始碼,否則驅動版本會與Boost版本不匹配,構建工程過程中會報某些lib無法找到的錯誤

4. 工程環境配置及連線測試

  • 工程環境配置

新建VS工程mongotest,配置依賴庫

屬性頁-VC++目錄-包含目錄新增Boost標頭檔案路徑和C++驅動標頭檔案路徑。庫目錄新增Boost lib路徑和C++驅動lib路徑。

我新增的分別是

D:\local\boost_1_60_0;E:\driver\mongo-cxx-driver-legacy-1.1.2\build\install\include;

E:\driver\mongo-cxx-driver-legacy-1.1.2\build\install\lib;D:\local\boost_1_60_0\lib32-msvc-10.0;

注意路徑深度與程式碼中的包含相匹配。

VC++目錄下路徑配置

連結器-輸入-附加依賴項新增依賴庫:mongoclient-gd.lib;

同時將boost_1_60_0\lib32-msvc-10.0路徑下的dll檔案和c++驅動路徑下的mongoclient-gd.lib檔案複製到新建工程exe檔案的同級目錄下。

  • 編寫測試程式碼
#include <WinSock2.h>
#include <windows.h>
#include <mongo/client/dbclient.h>
#include <string>
#include <iostream>

using namespace mongo;
using namespace std;

int main()
{
	string errmsg;
	client::initialize(); //初始化客戶端
	DBClientConnection *conn = new DBClientConnection(false, 0, 3);
	
	if(conn->connect("192.168.0.104:27017", errmsg))
	{
		cout << "conn ok :" << errmsg << endl;
	}
	else
	{
		cout << "conn err :" << errmsg << endl;
	}

    //查詢資料
	BSONObj obj;
	auto_ptr<DBClientCursor> cursor = conn->query("test.test", Query("{}"));
	while(cursor->more())
	{
		obj = cursor->next();
		cout << obj << endl;
	}

	system("pause");
	delete(conn);
	return 0;
}

該示例程式碼做了連線和簡單的查詢動作,可以將資料庫中的資料進行顯示。

這裡需要注意:

  1. 包含mongodb標頭檔案之前,需要首先包含windows相關標頭檔案
  2. windows下執行驅動,建立連線物件之前,首先要初始化:client::initialize();否則會連線失敗
  3. 連線之前需要修改mongodb server的配置檔案。還記得安裝server時指定的配置檔案嗎。
# mongodb.conf

# Where to store the data.
dbpath=/var/lib/mongodb

#where to log
logpath=/var/log/mongodb/mongodb.log

logappend=true

#bind_ip = 127.0.0.1
#這裡將本地迴環改成0.0.0.0,才能通過不同ip進行連線
bind_ip = 0.0.0.0
#port = 27017

# Enable journaling, http://www.mongodb.org/display/DOCS/Journaling
journal=true

# Enables periodic logging of CPU utilization and I/O wait
#cpu = true

# Turn on/off security.  Off is currently the default
#noauth = true
#auth = true

至此,安裝測試完畢,enjoy it