Finding data in mongodb by column name without a known _id - php

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.

Related

MongoDB / PHP / MapReduce / Reg Exp / Strings->Floats

I'm new with MapReduce, but I have a collection that I'd like to apply myself to as a chance to learn how mapreduce works.
Example Documents:
{ "filename" : "resume.doc",
"folder" : "work",
"completed": "0.5" },
{ "filename" : "spreadsheet.xls",
"folder" : "work",
"completed": "0.6" },
{ "filename" : "thesis.doc",
"folder" : "school",
"completed": "0.75" },
{ "filename" : "coverletter.doc",
"folder" : "work",
"completed": "0.6"}
So the whole idea is: I'd like to query:
{ "folder" : "work",
"completed": { $gt: 0.5 },
"filename" : new MongoRegex( "/\.[a-zA-Z]{2,}$/" ) }
And ultimately get the count of all documents by extension (.doc, .xls, etc.), as so:
{ ".doc" : 1,
".xls" : 1 }
I also realize i've got an issue because my %-completed are strings, not floats, so i think mongodb is going to need more instruction for comparing the strings.
I'm using (if it matters):
PHP extension: mongo/1.5.7
MongoDB: version 3.2.11
Seems I've stumbled upon my own answer.
Let me know if anybody comes up with a more concise/expert solution.
But this seems to work.
try {
$map = new MongoCode(
'function(){
var re = new RegExp(/(.+)\.([a-zA-Z]{2,})$/);
doctype = this.value.match(re);
if(parseFloat(this.completed)>0.5){
emit(doctype[2], parseFloat(this.completed));
}
}'
);
$reduce = new MongoCode(
'function(key, values){
var sum = 0, num = 0;
for(var i in values){
if(parseFloat(values[i])>0.5){
sum += values[i];
num += 1;
}
}
return { number_of_documents : num,
sum_of_document_completions : sum,
average_completion : (sum/num) };
}'
);
$query = array (
"folder" => "work"
);
$doctypes = $db->command(
array(
'mapReduce' => 'mydocuments',
"map" => $map,
"reduce" => $reduce,
"query" => $query,
"out" => array("inline"=>1)
)
);
print_r ( $doctypes);
}
catch(MongoCursorException $e) {
echo "error message: ".$e->getMessage()."\n";
echo "error code: ".$e->getCode()."\n";
}

Notice: Trying to get property of non-object in in json

<?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.

Mongodb Nested array value is empty always

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');

Yii, MongoDB query Subdocuments for insertion in a Mysql Table

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;
}
}

Rewrite manually created nested JSON to use PHPs built in functions

I have in my table records that are related one to another by a parentId field. When fetching them from the DB I need to create JSON array of objects where the child records are added to 'children' property of parent objects :
[{
//main object
children : [
{
//#1st level children object
children: [
{
//#2nd level children object
}
]
}
]
},
{
(...)
]
But if there are no records with parentId equal to current record, then this property shouldn't be added to the object.
Right now I'm building the JSON string manually :
//first get the parents
$q = 'SELECT * FROM table WHERE parentId = 0';
$r = mysql_query($q);
$x=1;
$nr = mysql_num_rows($r);
while($e = mysql_fetch_array($r)){
if($x==1){
echo '[ { ';
}
else{
echo ' { ';
}
if($e['leaf']==1){
$leaf = 'true';
} else {
$leaf = 'false';
}
echo '"EndDate" : "'.str_replace('T00:00:00','',$e['EndDate']).'",
"Id" : '.$e['Id'].',
"Name" : "'.$e['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e['BaselineStartDate']).'"';
if($leaf){
echo ',"leaf": '.$leaf.'';
}
childs($e['Id'], $x, $nr);
if($x<$nr){
echo ',';
}
$x++;
}
if($x>1){
echo ']';
}
function childs($id, $x, $nr, $x2='', $nr2=''){
//now see if there are childern
$q2 = 'SELECT * FROM table WHERE parentId = "'.$id.'" ';
$r2 = mysql_query($q2);
$nr2 = mysql_num_rows($r2);
if($nr2>0){
echo ',"children": [ ';
$x2 =1;
while($e2 = mysql_fetch_array($r2)){
if($e2['leaf']==1){
$leaf2 = 'true';
}
else{
$leaf2 = 'false';
}
echo '{
"EndDate" : "'.str_replace('T00:00:00','',$e2['EndDate']).'",
"Id" : '.$e2['Id'].',
"Name" : "'.$e2['Name'].'",
"BaselineStartDate" : "'.str_replace('T00:00:00','',$e2['BaselineStartDate']).'",
"leaf" : "'.$leaf2.'"';
childs($e2['Id'],$x,$nr,'',$x2,$nr2);
if($x2<$nr2){
echo ',';
}
$x2++;
}
echo '] }';
}
else{
echo ',"children" : []}';
}
}
Is there an easy way to make this code more robust using some built-in PHP features like fetch_assoc or something like that?
You should rather..
Fetch the results from the database
Reformat as per the requirement (related code you can use with some alteration PHP Create a Multidimensional Array from an array with relational data
Then finally, json_encode the resulting array

Categories