[英]storing live data in Mongodb
我正在使用網站上的API將數據推送到服務器。 每當我的arduino檢測到一個脈沖時,就會將其發送到COSM。 通過使用觸發器,數據將發送到我的服務器。 我最初是將數據寫入.txt文件和Json對象,但現在我想開始實現mongo以具有不同的集合。
由於某種原因,當我嘗試將其寫為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);
?>
這可能是您出現問題的根源:
//A loop to populate
foreach($json as $data){
$collection->insert($data);
}
您正在遍歷$ json數組,並將值(但不是鍵)傳遞給MongoCollection的insert方法。 根據文檔,此方法需要一個對象或數組。 根據我的理解,您要嘗試執行此foreach循環的代碼應替換為以下內容:
$collection->insert($json);
這將創建一個類似於您的數組的mongo對象。 您的代碼當前正在嘗試將每個數組元素的值作為一個單獨的條目插入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.