前边有简单说过关于mongodb fdw 容器构建的,一些是一些使用上的简单说明
环境准备
- docker-compose 文件
version: "3"
services:
pg-mongo:
image: dalongrong/pgspider:mongo
ports:
- "5432:5432"
environment:
- "POSTGRES_PASSWORD:dalong"
mongo:
image: mongo
ports:
- "27017:27017"
- 初始化mongodb 数据
主要包含创建用户以及初始化数据库还有简单的集合数据
use apps
db.createCollection("apps")
db.createUser(
{
user: "dalong",
pwd: "dalong",
roles: [{role: "dbAdmin", db: "apps"}],
mechanisms : ["SCRAM-SHA-1"]
}
)
demo 数据
/* 1 */
{
"_id" : ObjectId("5e45fbd905d1df732b82b607"),
"items" : [
1,
3,
4
],
"userinfo" : {
"username" : "dalong",
"userage" : 33
}
}
/* 2 */
{
"_id" : ObjectId("5e4601d905d1df732b82b6fa"),
"items" : [
11,
31,
41
],
"userinfo" : {
"username" : "dalong1",
"userage" : 3
}
}
/* 3 */
{
"_id" : ObjectId("5e4601e905d1df732b82b6fe"),
"items" : [
12,
31,
41
],
"userinfo" : {
"username" : "dalong",
"userage" : 3
}
}
使用扩展
- 启动服务
docker-compose up -d
- 使用扩展
CREATE EXTENSION mongo_fdw;
// 创建server
CREATE SERVER mongo_server FOREIGN DATA WRAPPER mongo_fdw OPTIONS (address 'mongo', port '27017', authentication_database 'apps');
// 创建用户映射
CREATE USER MAPPING FOR postgres SERVER mongo_server OPTIONS(username 'dalong', password 'dalong');
// 创建外部表方法一,使用table 定义,注意对于嵌套json 对象的支持通过<key>.<filed>" 格式
CREATE FOREIGN TABLE userapps(_id NAME,items int[],"userinfo.userage" int,"userinfo.username" text) SERVER mongo_server OPTIONS (database 'apps', collection 'myapps');
// 创建外部表方法二 使用jsonb 格式定义,方便使用json 函数,但是比较json 支持没有sql 功能强大
CREATE FOREIGN TABLE userapps_json(__doc jsonb) SERVER mongo_server OPTIONS (database 'apps', collection 'myapps');
// 数据查询
select * from userapps;
// 数据查询
select * from userapps_json;
// jsonb 格式查询
SELECT __doc ::jsonb->'userinfo' as usereinfo FROM userapps_json WHERE __doc ::jsonb->'userinfo'->>'username'='dalong';
效果
参考资料
https://github.com/EnterpriseDB/mongo_fdw/blob/master/sql/mongo_fdw.sql
https://www.postgresql.org/docs/11/functions-json.html
https://github.com/rongfengliang/pgspider-docker
https://github.com/rongfengliang/pgspider-mongo-fdw-learning
https://hub.docker.com/repository/docker/dalongrong/pgspider