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
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.
To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With