So I am using MongoDB and PHP for the first time and I am getting stuck at the following problem:
I want to insert an object into an array. The inserting is not really the problem but the specifying in which document and in which place in the document is more the problem.
My mongoDB document
_id:6235ef5e2a9b6d72904a1fc3
username:"Josse"
email:"josse#mail.nl"
password:"1234"
level:1
domainArray:Array
0:Object
domainname:"josse.com"
domainvalue:9
ouputArray:Array
0:Object
1:Object
domainname:"example.com"
domainvalue:9
ouputArray:Array
0:Object
The desired document:
_id:6235ef5e2a9b6d72904a1fc3
username:"Josse"
email:"josse#mail.nl"
password:"1234"
level:1
domainArray:Array
0:Object
domainname:"josse.com"
domainvalue:9
ouputArray:Array
0:Object
1:Object
domainname:"example.com"
domainvalue:9
ouputArray:Array
0:Object
outputname:"output1"
outputdate:"23/03/2022"
The problem:
I would like to be able to specify that I want to add the outputname and date into the ouputArray that is inside the object with domainname "example.com"
What I have tried:
After some research I found that in MongoDB multiple query parameters is a thing, but I can't seem to make it work using PHP.
My code:
public function addOuput($ouputData, $username){
$collection = $collection = (new MongoDB\Client('mongodb://localhost:27017'))->mydb->users;
$insertOneResult = $collection->updateOne(
["username" => "josse.com"],
['$addToSet' => ["domainArray.$[].ouputArray" => $ouputData]] );
}
When I use this code the $outputData gets added into every object that is inside the domainArray which I do not want. I only want it added into the object that is inside domainArray that I specify.
public function addOuput($ouputData, $username){
$collection = $collection = (new MongoDB\Client('mongodb://localhost:27017'))->mydb->users;
$insertOneResult = $collection->updateOne(
["username" => "josse.com", "domainArray.domainname"=>"josse.com"],
['$addToSet' => ["domainArray.$[].ouputArray" => $ouputData]] );
}
The code above is what I have tried to make it work, but this is not the way to go since it did not give me errors, but also added nothing into the database.
Can anyone help me with my problem?
Thanks in advance!
Related
I'm using jasperserver in my php/Symfony to generate my reports, and i pass parameters ad everything works fine. But now i want to pass an array containing the list of my user's name to jrxml file i really don't know if it's possible. i mean i know that we can do it with javabeans or creating a datasource, but in my case i mustn't use a database plus i use php.
So if anyone know how to pass the array and fetch it in the jrxml file to display all the values i would be so grateful
so here is the code i'm want to use
$users = $em->getRepository('UserBundle:Utilisateur')->getAll();
$params = array(
"montantEnLettre" => $montantEnLettre,
"policeGroupeLibelle" => $contrat->getProduit()->getLibelle(),
"montanttotal" => $contrat->getMontantTotale(),
"utilisateurs" => $users
);
$d = new Client(
"http://127.0.0.1:8080/jasperserver",
"jasperadmin",
"jasperadmin"
);
$js = $d->jobService();
$d->setRequestTimeout(60);
$info = $d->serverInfo();
$report = $d->reportService()->runReport('/reports/epargne', 'pdf',null,null,$params);
I don't know if i can pass the users as a parameter and i have no idea how to fetch it my jrxml file
I have some documents in mongodb that look like this
{ "_id" : ObjectId("576f46ca6803fab30e7b23c8"),
"username" : "Dallas",
"likes" : [ "576f46ca6803fab30e7b23c8", "576f4c446803faae0e7b23c9" ]}
{ "_id" : ObjectId("576f46ca6803fab31e7b23c8"),
"username" : "Dallas",
"likes" : [ ]}
<?php
$m = new MongoClient();
$db = $m->testing;
$collection = $db->testCollection;
addLike();
//Add likes
function addLike()
{
$id = new MongoId("576f46ca6803fab30e7b23c8");
$collection->update(array('_id' => $id),array('$addToSet' => array('likes' => '4d0b9c7a8b012fe287547157')));
echo 'addLike seemed to work';
}
I know the line of code that is wrong (syntax-wise I'm guessing) is the line that does the ...->update()
If i comment this out, I make it to the echo.
What I'm trying to do is store all of the user ids inside of the likes array, as you see one of the posts has an empty array, that's how I plan to start all posts.
I am confused as to why this code doesn't work, I pretty much copied it directly from here
EDIT:
To add, I really like what the above post says about it not allowing it to make duplicates when using $addToSet. As it shouldn't be possible for the user to like a post more than once, there is never a time the id should be in more than once
It appears all of my code was actually correct, except for some failure to understand php syntax.
I was under the impression that creating a collection variable outside of the function was global, It turned out that it didn't want me to call collection inside of that function so by deleting the function it was fixed.
I'm able to query my dynamodb tables, but I only want to retrieve the actual value. I don't want the formatting output. This same question has been answered here for Java, but I'm looking for the PHP solution:
Retrieving just the item value from a dynamodb table?
Here is my getitem query:
$response = $dynamodb->getItem(array(
"TableName" => $tableName,
"ConsistentRead" => true,
"Key" => array(
"userguid" => array(Type::STRING => $userguid)
),
"AttributesToGet" => array("token")
));
print_r($response["Item"]["token"]);
Here is the output:
Array
(
[S] => 9d194513
)
All I want to get back is:
9d194513
I assumed the logical answer would be to change the last line to:
print_r($response["Item"]["token"]["S"]);
But then my code doesn't return anything at all. Obviously still learning PHP here, and any help would be appreciated.
Don't use print_r function, just either echo your variables
echo $response["Item"]["token"]["S"];
or store in a variable for later use
$res_token = $response["Item"]["token"]["S"];
You can also use the getPath convenience method built into the Model object that the SDK returns for operations.
echo $response->getPath('Item/token/S');
For more information about working with responses in the SDK, see the Response Models page in the AWS SDK for PHP User Guide.
Though it's an old question but for anyone coming to this page for seeking answer, this is how I have done it.
getItem returns a Resultobject. You can call the get() function of the SDK, which will give you an array containing the exact value.
$params = [
"TableName" => "EpgApiAccessCount",
"Key" => $this->marshalJson('
{
"ApiUserKey": "' . $apiUserkey . '"
}
')
];
$result = $this->client->getitem($params);
if (!$result instanceof ResultInterface) {
return 0;
}
$item = $this->unmarshalItem($result->get("Item"));
return $item["AccessCount"];
Of course your value and table name will be different, and you can print or do anything else with the value.
I want save many files using MongoDB's GridFS but I ran into some trouble by using my own id. My simplified code is the following:
<?php
$mongo = new Mongo();
$db = $mongo->myFiles;
$grid = $db->getGridFS();
var_dump($grid->storeBytes("ForTestingPurposes", array("_id" => new MongoID("mySampleId"), array("safe" => true))));
?>
I assumed that storeBytes() returns my own id (in this case "mySampleId") but what I get is something like this:
object(MongoId)#5 (1) { ["$id"]=> string(24) "50ae7542a34156852300003d" }
.. the automatically generated ID from Mongo. Is there anything wrong with my code above? Thanks for any suggestions...
The PHP MongoId class is only for working with MongoDB ObjectIDs, which have a specific 12-byte format.
If you want to use a custom value for _id, just pass the string directly, eg:
$grid->storeBytes("ForTestingPurposes", array("_id" => 'mySampleId', array("safe" => true))));
I'm having an annoying problem. I'm trying to find out what fields of a form were changed, and then insert that into a table. I managed to var_dump in doUpdateObjectas shown in the following
public function doUpdateObject($values)
{
parent::doUpdateObject($values);
var_dump($this->getObject()->getModified(false));
var_dump($this->getObject()->getModified(true));
}
And it seems like $this->getObject()->getModified seems to work in giving me both before and after values by setting it to either true or false.
The problem that I'm facing right now is that, some how, sfWidgetFormSelect seems to be saving one of my fields as a string. before saving, that exact same field was an int. (I got this idea by var_dump both before and after).
Here is what the results on both var dumps showed:
array(1) {["annoying_field"]=> int(3)} array(1) {["annoying_field"]=>string(1)"3"}
This seems to cause doctrine to think that this is a modification and thus gives a false positive.
In my base form, I have
under $this->getWidgets()
'annoying_field' => new sfWidgetFormInputText(),
under $this->setValidators
'annoying_field' => new sfValidatorInteger(array('required' => false)),
and lastly in my configured Form.class.php I have reconfigured the file as such:
$this->widgetSchema['annoying_field'] = new sfWidgetFormSelect(array('choices' => $statuses));
statuses is an array containing values like {""a", "b", "c", "d"}
and I just want the index of the status to be stored in the database.
And also how can I insert the changes into another database table? let's say my Log table?
Any ideas and advice as to why this is happen is appreciated, I've been trying to figure it out and browsing google for various keywords with no avail.
Thanks!
Edit:
ok so I created another field, integer in my schema just for testing.
I created an entry, saved it, and edited it.
this time the same thing happened!
first if you what the status_id to be saved in the database, you should define your status array like this:
{1 => "a", 2 => "b", 3 => "c", 4 => "d"}
So that way he know that 1 should be rendered like "a" and so on. Then, when saving, only the index should be saved.
About saving in another database, my advise is to modify the doSave method defined by the Form class yo match your needs. I only know how Propel deals with it, maybe this could help:
the doSave method dose something like this:
protected function doSave($con = null)
{
if (null === $con)
{
$con = $this->getConnection();
}
$old = $this->getObject()->getModifiedValues($this);//Define this
$new_object = new Log($old);//Create a new log entry
$new_object->save($con));//save it!
$this->updateObject();
$this->getObject()->save($con);
// embedded forms
$this->saveEmbeddedForms($con);
}
Hope this helps!
Edit:
This is an example extracted from a model in one of my applications and its working ok:
Schema:
[...]
funding_source_id:
type: integer
required: true
[...]
Form:
$this->setWidget('funding_source_id', new sfWidgetFormChoice(array(
'choices' => array(1 => 'asdads', 2 => '123123123' , 3 => 'asd23qsdf'),
)));
$this->setValidator('funding_source_id', new sfValidatorChoice(array(
'choices' => array(1 => 'asdads', 2 => '123123123' , 3 => 'asd23qsdf'),
'required' => true
)));
About the log thing, that could be quite more complex, you should read the current implementation of the doSave method in the base form class, currently sfFomrObject on Symfony1.4., and when and how it delegates object dealing with modified values.
Okay,
It turns out I forgot to do a custom validator to use the array key instead.