Mongodb gives the following:
{
"_id" : ObjectId("55d1d8ea464498a8338b4567"),
"appuserfirstname" : "Bhatti",
"appuserlastname" : "Singh",
"appusermiddlename" : "Tripatpal",
"appuseremail" : "tripat.90#gmail.com",
"appusergoogleid" : [
{ "id" : "APA91bFPqNjK5bWdTe6bAniDV8ZlmG5vL3Q1qRz_WGAasOMu_WBbzoorWI2uCU7yC4IS-yggNGQvL7oUp5YhiejOC1TB4bFQspKj4AUZ05-IEL9DJiI2oNwIl5YwW5zyBVqrTMNWFF2B" }
],
"usercreationdate" : ISODate("2015-08-17T18:21:54Z"),
"status" : "0",
"userfollows" : [
{ "following" : ObjectId("55cd8dae46449867738b4567") }
]
}
I want the ids that are in following. but it always gives me empty string
<?php
$appuserid = '123456789';
$appuserscollection = $this->database->createCollection("appusers");
$followers = array('_id' => new MongoId($appuserid));
$s = "";
$result = $appuserscollection->find($followers);
foreach($result as $document) {
$s.=$document['userfollows'];
}
echo $s;
?>
With
$appuserscollection = $this->database->createCollection("appusers");
you create a new collection. And a new collection is always empty
you could try
$collection = new MongoCollection($this->database, 'appusers');
Related
I want to select id and property_name just like i would on mysql
select property_name,_id from properties from properties
In mongodb that is
> db.properties.find({
...
... },{
... "property_name": 1
... }
... );
{ "_id" : ObjectId("6098e4743569ea6d9d6985b2"), "property_name" : "Aero Club" }
{ "_id" : ObjectId("6098f8e7a3397059ef264932"), "property_name" : "Radisson Blu Hotel" }
>
This is my php code
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->hotel->properties;
//echo $collection->count();
echo "<pre>";
print_r($collection->find(array(), array("property_name" => 1))).iterator_to_array();
echo "</pre>";
I don't see the array of id and property_name returned anywhere so its hard fro me to loop through the returned object.
After returning the id and property, i wan't to translate this query into mongodb
select * from rooms where (has_sauna = 'yes' OR has_elevator = 'yes' or has_television = 'yes') and (price between "200" and "300" )
How can i fix the php query?.
Have you tried this one?
$collection->find(
{ $and: [
{ $or: [
{has_sauna : 'yes'},
{has_elevator : 'yes'},
{has_television : 'yes'}
]},
{ price: {$gt : 200, $lt : 300} }
]}
);
I can get the id and property name like this
$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->hotel->properties;
$cursor = $collection->find();
foreach ($cursor as $document) {
echo '"_id": '.$document["_id"]."<br />";
echo '"property name": '.$document["property_name"]."<br />";
}
While this works, i would like to know how to specify what columns/fields to find.
This is the return result of my two variables:
$resultPayment = [
[72875500, 8187000],
[14343],
[44419200,
["12332000"],
[28700250]
]
$resultId = [
["461", "462"],
[6462],
[8771],
[8461],
[5461]
]
This is the code for get the data:
for ($iii=0; $iii<count($dataInvoice); $iii++) {
$resultId[] = unserialize($dataInvoice[$iii]->invoiceid);
$resultPayment[] = unserialize($dataInvoice[$iii]->jumlahbayarid);
}
These two pieces of data are the same length and array structure, and I want to combine $id and $payment and create an object. Here are the results I expect :
[
{ "461": 72875500 },
{ "462": 8187000 },
{ 6462: 14343 },
{ 8771: 44419200 },
{ 8461: "12332000" },
{ 5461: 28700250 }
]
One possible approach is the following example:
<?php
$payment = [
[72875500, 8187000],
[14343],
[44419200],
["12332000"],
[28700250]
];
$id = [
["461", "462"],
[6462],
[8771],
[8461],
[5461]
];
$payment = call_user_func_array('array_merge', $payment);
$id = call_user_func_array('array_merge', $id);
$result = json_encode(array(array_combine($id, $payment)));
echo $result;
?>
Result:
[{"461":72875500,"462":8187000,"6462":14343,"8771":44419200,"8461":"12332000","5461":28700250}]
<?php
$json= '{
"fields" :
[
{
"name" : "news_title",
"type" : "text",
"value" : "old title"
},
{
"name" : "news_content",
"type" : "textarea",
"value" : "old content"
}
]
}';
echo $json;
$jsonInPHP = json_decode($json,true);
$results = count($jsonInPHP['fields']);
for ($r = 0; $r < $results; $r++){
// look for the entry we are trying to find
if ($jsonInPHP->fields[$r]['name'] == 'news_title'
&& $jsonInPHP->fields[$r]->value == 'old title'){
// remove the match
unset($jsonInPHP->fields[$r]);
if(empty($jsonInPHP->fields[$r]->value))
{
$jsonInPHP['fields'][$r]['name'] == 'news_title';
$jsonInPHP->fields[$r]->value=='no';
}
break;
}
}
function gog($status)
{
$results = count($status->fields);
for ($r = 0; $r < $results; $r++){
$status->fields[$r]->value == 'old rr';
}
}
$jsonInPHP->fields = array_values($jsonInPHP->fields);
echo json_encode($jsonInPHP);
?>
i want to change after searching from
'{"fields":[{"name":"news_title","type":"text","value":"old title"},{"name":"news_content","type":"textarea","value":"old content"}]}'
to
'{"fields":[{"name":"news_title","type":"text","value":"My new title"},{"name":"news_content","type":"textarea","value":"My new content"}]}'
Check official docs of json_decode Second parameter of function json_decode($json,true); (in your case true) determines whether result will be converted to associative array. If you want to use result as objects set that value to false or better omit that at all.
So I have this JSON for example
{
"top" : [
{
"info" : {
"ID" : 0,
"TID" : 1
},
"geo" : {
"poins" : [
[
[
-5.9,
57.1
],
[
-5.99,
57.0
]
]
]
}
},
{
"info" : {
"ID" : 1,
"TID" : 2
},
"geo" : {
"points" : [
[
[
-5.4,
57.0
],
[
-5.9,
57.0
]
]
]
}
}
]
}
I need to put this information in the DataBase with php
So I have a colum in the DB called points and it need the data inside to be looking like:
[-5.4, 57.0],[-5.9, 57.0]
I have a columb with ID so all I need is to put the points from the JSON for every ID
My php should be loking like:
connection to the database
$str = file_get_contents(the JSON);
$json = json_decode($str, true);
foreach ($json['top'] as $field) {
query='UPDATE poins_table
SET points='$field['geo']['points']'
WHERE ID='$field['info']['ID']' '
}
The code seems to be not working. What I am missing ...Any siggestions will be helpfull. Thank you
You could try following:
<?php
$str = file_get_contents('the JSON URL');
$json = json_decode($str, true);
try{
$db = new PDO("dbtype:host=yourhost;dbname=yourdbname;charset=utf8","username","password");
$query = $db->prepare('UPDATE poins_table SET points=? WHERE ID=?');
foreach ($json['top'] as $field) {
$query->execute(array(json_encode($field['geo']['points']), $field['info']['ID']));
}
} catch(PDOException $e) {
echo "Error: ". $e;
}
?>
I'm doing a project using Yii Framework, MySQL and MongoDB. I need to get the data from a collection of the mongo database and insert the records in a mysql table. The document of mongodb has subdocuments and I need to insert a row in mysql for every subdocument in the collection. The code of my project is:
$query = array('year'=>'2014');
$records = Yii::app()->edmsMongoCollection('DocumentosDesgloseER')->find($query);
foreach($records as $data){
$success = false;
$model = new DesgloseAcumulado;
$atributos['Id_Enterprise'] = $data['id_enterprise'];
$atributos['Id_Store'] = $data['id_store'];
$atributos['Month'] = $data['month'];
$atributos['Year'] = $data['year'];
$atributos['Id_Usuario'] = Yii::app()->user->id;
$atributos['Id_RubroER'] = $data['DocumentosDesgloseER'][0]['id_rubroer'];
$i = $i + 1;
$model->attributes = $atributos;
if($model->save()) {
$success = true;
}
}
And the structure of my collection in mongodb is:
{
"_id" : ObjectId("535fe63acac5853943166f5c"),
"DocumentosDesgloseER" : [
{
"elemento" : "VENTAS NETAS",
"id_rubroer" : "45",
"id_documento_consolidados_temp" : "31809",
"abreviatura" : "VN",
"orden" : "1",
"formula" : "(250*CM)",
"tipo_fila" : "1",
"resultado_actual" : "113.628",
"resultado_ant" : "239.851",
"promedio_mensual_actual" : "111.365",
"ppto_mes_actual" : "131.540",
"real_acumulado_actual" : "556.826",
"real_acumulado_ant" : "965.824",
"ppto_acumulado_actual" : "666.805"
},
{
"elemento" : "RUBRO DE PRUEBAS",
"id_rubroer" : "19",
"id_documento_consolidados_temp" : "31810",
"abreviatura" : "RP",
"orden" : "3",
"formula" : "CM/500",
"tipo_fila" : "1",
"resultado_actual" : "71.057",
"resultado_ant" : "281.697",
"promedio_mensual_actual" : "67.090",
"ppto_mes_actual" : "72.347",
"real_acumulado_actual" : "335.448",
"real_acumulado_ant" : "879.719",
"ppto_acumulado_actual" : "366.743"
}
],
"documentoID" : "4DOTA2",
"id_enterprise" : "1",
"id_store" : "24",
"month" : "Importes2",
"year" : "2014",
"lastMonthNumber" : NumberLong(4)
}
This is only one of the documents in the collection. As I said earlier, I need to save a row for every subdocument for each document in the mysql database. My code save only the data of the document and the id_rubroer of the subdocument "0".
Does anyone know how I can make the For Loop for each subdocument rather than for each object (document)?
Thanks
Just for-loop the "sub-documents"... say:
foreach($records['DocumentosDesgloseER'] as $data){
$success = false;
$model = new DesgloseAcumulado;
$atributos['Id_Enterprise'] = $data['id_enterprise'];
$atributos['Id_Store'] = $data['id_store'];
$atributos['Month'] = $data['month'];
$atributos['Year'] = $data['year'];
$atributos['Id_Usuario'] = Yii::app()->user->id;
$atributos['Id_RubroER'] = $data['id_rubroer'];
$i = $i + 1;
$model->attributes = $atributos;
if($model->save()) {
$success = true;
}
}