我要将当前的PostgreSQL数据库转换为MongoDB版本。例如,我有一个表来记录推文,另一个表来记录特定推文使用的多个主题标签。我想做的是使用SQL获取如下表格,然后将其导出为.csv文件,以便我可以将其导入MongoDB。
示例:
2018-04-02 18:12:32 This plane has no outlet for me to charge my p... [{'tag': 'GucciGarden', 'airline': 'American A...
我遇到的问题是我可以得到一个.csv文件包含像"[{'tag': 'GucciGarden', 'airline': 'American A..."
这样的json数组,但它是一个String类型!当我将它导入MongoDB时。引用将被保留,这使得错误。
这是我的SQL代码:
SELECT tweets.tweet_id,tweets.text,
(SELECT array_to_json(array_agg(row_to_json(d)))
from (
SELECT tags.tag
FROM
tags
WHERE tags.tweet_id=tweets.tweet_id
) d
) as Tags
from tweets
以下是我导入MongoDB的结果:
{
"_id" : ObjectId("5ac59c272221ade1185ec241"),
"tweet_id" : 9.80869021435351e+17.0,
"created_at" : "2018-04-02 18:06:13",
"text" : "RT @MiraSorvino: Brad Myles shares @Delta that awareness is working- 9,000 #humantrafficking cases identified by @polarisproject National H��",
"screen_name" : "MMexville",
"favorite_count" : 0.0,
"retweet_count" : 40.0,
"source" : "the public",
"tags" : "[{'tag': 'humantrafficking', 'airline': 'Delta Air Lines'}]"}
答案 0 :(得分:1)
这是因为[{'tag':
不是有效的json - 你应该使用双引号并强制转换为json,例如:
让我们说样品就像你一样:
t=# create table c (i int, t text, j text);
CREATE TABLE
t=# insert into c values(1,'text',$$[{'tag': 'GucciGarden'}]$$);
INSERT 0 1
t=# select * from c;
i | t | j
---+------+--------------------------
1 | text | [{'tag': 'GucciGarden'}]
(1 row)
所以那就像你的qry一样:
t=# select to_json(c) from (select i,t,replace(j,$$'$$,'"')::json j from c) c;
to_json
-------------------------------------------------
{"i":1,"t":"text","j":[{"tag": "GucciGarden"}]}
(1 row)
当然,你会对单引号有正面的错误替换,例如'tag': 'Gucci's Garden'
将破坏查询逻辑,因此你必须做出更复杂的替换。可能正则表达式更整洁。