FDW for MongoDB

1. 准备Mongo环境

MongoDB环境:

Host: 127.0.0.1
Port: 5888
User: mongo_user
Database: mongo_pass

2. 在MatrixDB中创建FDW

下面登录MatrixDB,使用mongo_fdw连接MongoDB:

首先要在集群所有主机上安装mongo客户端库。

首先,创建mongo_fdw扩展:

mxadmin=# create extension mongo_fdw;
CREATE EXTENSION

创建Mongo服务器定义:

mxadmin=# CREATE SERVER mongo_server FOREIGN DATA WRAPPER mongo_fdw OPTIONS (address '127.0.0.1', port '5888');
CREATE SERVER

创建用户映射:

mxadmin=# CREATE USER MAPPING FOR postgres
    SERVER mongo_server
    OPTIONS (username 'mongo_user', password 'mongo_pass');
CREATE USER MAPPING

创建外部表:

mxadmin=# CREATE FOREIGN TABLE warehouse
    (
        _id name,
        warehouse_id int,
        warehouse_name text,
        warehouse_created timestamptz
    )
    SERVER mongo_server
    OPTIONS (database 'db', collection 'warehouse');
CREATE FOREIGN TABLE

3. 使用mongo_fdw读写数据表

外部表创建成功后,下面就可以通过直接读写外部表来实现对MongoDB中的test表的操作。

3.1 查询数据

在MongoDB中查询:

db.warehouse.find
(
    {
        "warehouse_id" : 1
    }
).pretty()
{
    "_id" : ObjectId("53720b1904864dc1f5a571a0"),
    "warehouse_id" : 1,
    "warehouse_name" : "UPS",
    "warehouse_created" : ISODate("2014-12-12T07:12:10Z")
}

使用mongo_fdw在MatrixDB中查询:

mxadmin=# SELECT * FROM warehouse WHERE warehouse_id = 1;
           _id            | warehouse_id | warehouse_name |     warehouse_created
--------------------------+--------------+----------------+---------------------------
 53720b1904864dc1f5a571a0 |            1 | UPS            | 2014-12-12 12:42:10+05:30
(1 row)

3.2 写入数据

向外部表插入数据:

mxadmin=# INSERT INTO warehouse VALUES (0, 2, 'Laptop', '2015-11-11T08:13:10Z');
INSERT 0 1