Я нажимаю данные на сервер, используя API с веб-сайта. Каждый раз, когда мой ардуинец обнаруживает импульс, он посылает его в COSM. И с помощью триггера данные поступают на мой сервер. Сначала я записывал данные в файл .txt и объект Json, но теперь я хочу начать реализацию mongo, чтобы иметь разные коллекции.Сохранение данных в реальном времени в Mongodb
По какой-то причине данные не передаются на мой сервер после того, как я добавил соединение Mongo, когда попытался написать его как коллекцию Mongo. Я хочу иметь возможность напрямую записывать информацию в Mongo и не создавать файлы.
Любое предложение более чем приветствуется, вот код:
<?php
// Creating a data base in Mongodb to store my information from my $jsonFile
$connection = new MongoClient(); //Connect to mongo
$db = $connection -> qandm; // select my DB which is called qandM
$collection = $db -> pulseData;
//Gets all the information from Cosm
$pulse = $_POST['body'];
//access and open a file
//echo $pulse;
//Converts the data into PHP arrays
$pulseObj = json_decode($pulse, true);
//Parse through the specific information from the array and gets each piece of information in an array
$userName = $pulseObj["triggering_datastream"]["id"];
$dataTime= $pulseObj["triggering_datastream"]["at"];
$dataValue= $pulseObj["triggering_datastream"]["value"]["value"];
//Writes all the data coming from COSM
$file = fopen("data.txt", "a+");//a+ give the option to have the cursor at the end to access the file read and write it
/* $pulse.="\r\n"; */
fwrite($file, $pulse);//takes incoming data and writes it in the file
fclose($file);
//Opens a new .txt file and writes the values that we selected before into our file
$string = $userName." ".$dataTime." ".$dataValue." \r\n";
//error_log allows me to see in my Apache log server the information that I'm printing
error_log($string);
//Write all the information I parsed in my three variables in a new file
$file2 = fopen("rawData.txt", "a+");
fwrite($file2,$string);
fclose($file2);
//json sample
//Inputs the data from the time and the pulse value into a json object
$json = array("User" => $userName, "timestamp"=> $dataTime, "value"=> $dataValue);
//Opens a new json object
$jsonFile = fopen("data.json", "a+");
//Writes the data of our new arrayed information into the open json object
fwrite($jsonFile, json_encode($json));
fclose($jsonFile);
//A loop to populate
foreach($json as $data){
$collection->insert($data);
}
//find the data I just stored
$cursor = $collection->find();
//Output it in a UL
echo "<p> My Pulse </p>";
echo '<ul>';
foreach($cursor as $doc){
echo' <li> My pulse is: '.$doc['value'];
}
echo '</ul>';
/*$data = "data.txt";
$fh = fopen($data, "w") or die ("can't open file");
$data = json_encode($_POST);
fwrite($fh, $data);
fclose($fh);*/
//print_r($file);
?>
Сэм, большое спасибо за ваш ответ, какая небольшая ошибка у меня была. По какой-то причине то, что я хотел сделать с foreach(), было присвоение уникальной _id каждой приходящей строке из моего датчика пульса, который посылает 3 значения. Но это отлично работает! Еще раз спасибо! – mauricioSanchez