Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert JSON into MongoDb directly from PHP

Tags:

json

php

mongodb

I have an Android application which sends json data to PHP script. The PHP script have to save the data into MongoDB.

When I insert the data, MongoDB treat this data as a string.

$conn = new Mongo('mongodb://127.0.0.1:27017');

// access database
$db = $conn->Data;

// access collection
$collection = $db->Collection;
$collection->insert($myjson)

How can I say to MongoDB PHP driver that it is already a json document?

Thanks

like image 289
hotips Avatar asked Nov 10 '11 01:11

hotips


People also ask

Can we insert JSON into MongoDB?

The process to import JSON into MongoDB depends on the operating system and the programming language you are using. However, the key to importing is to access the MongoDB database and parsing the file that you want to import. You can then go through each document sequentially and insert into MongoDB.

How manually insert data in MongoDB?

To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.

Can I connect MongoDB in PHP?

You can add the driver to your application to work with MongoDB in PHP. The MongoDB PHP Driver consists of the two following components: The extension , which provides a low-level API and mainly serves to integrate libmongoc and libbson with PHP.

What is JSON format in MongoDB?

JSON is a data format that represents the values of objects, arrays, numbers, strings, booleans, and nulls. The Extended JSON format defines a reserved set of keys prefixed with " $ " to represent field type information that directly corresponds to each type in BSON, the format that MongoDB uses to store data.


1 Answers

The PHP MongDB Driver accepts arrays for inserts and queries (see here: http://www.php.net/manual/en/mongo.queries.php)

So you need to convert your JSON to an array.

Luckily, in general this is quite easy ... here is a snippet from a longer piece of code (see this article) to insert JSON data from the Twitter API into an array, then into MongoDB:

// Convert JSON to a PHP array
$usertimeline = json_decode($usertimeline);

// Loop array and create seperate documents for each tweet
foreach ($usertimeline as $id => $item) {
   $collection->insert($item);
}

Note the json_decode() function can convert to an array by passing true as the second parameter.

like image 140
Justin Jenkins Avatar answered Oct 08 '22 20:10

Justin Jenkins