duanqian6982 2018-06-11 04:57
浏览 217

从php7将json插入Mongodb

I'm working on a migration project from php5.6 to 7.x in which I have a json with special characters in keys. How can I insert this to mongodb?

In php5.6 I was using MongoClient as the driver which internally converts the special characters and hence I was able to insert the document. But I'm not able to achieve the same in php7. I'm using MongoDB\Driver\Manager to connect to Mongodb.

EDIT:

I have a set of api's coming from another system with the below format

$content_array=
{
    "context": {
        "extensions": {
            "http://id.tincanapi.com/extension/platform": "web",
            "http://id.tincanapi.com/extension/browser-info": "Mozilla/5.0",
            "http://id.tincanapi.com/extension/host-session-id": "4e320015"
        }
    }
}
$dbconnection = new MongoDB\Client($uri);
$db = $dbconnection->$dbname;
$collection = $db->$dbcoll;

$collection->insertOne(json_decode($content_array));

It fails in the above , saying "Invalid document for insert: keys cannot contain \".\":in the key". I understand its a not a good practice to use these characters in the key, however since this piece of code works in php5.6 using MongoClient I wanted to keep the changes as minimal as possible when migrating to php7.

EDIT 2:

The piece of code which works in php5.6

$dbconnection = new \MongoClient($dbhost, $options); 
if (!empty($dbconnection)) {
$db = $dbconnection->selectDB($dbname);
$collection = $db->selectCollection($dbcoll);
$status = 0;
if (!empty($collection)) {
$collection->insert(json_decode($content_array));
$status = 1;
}

EDIT3:

part of me was wrong in not giving all details at once.. i do a json_decode to convert to native php array before inserting to mongo.

Any help would be appreciated. Thanks.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
    • ¥15 unity连接Sqlserver
    • ¥15 图中这种约束条件lingo该怎么表示出来
    • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
    • ¥15 流式socket文件传输答疑
    • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
    • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
    • ¥15 win10,这种情况怎么办
    • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
    • ¥100 在连接内网VPN时,如何同时保持互联网连接