MongoDB & PHP | How to add object into existing document? - php

I am very new to MongoDB and PHP and I am trying to add an object into an already existing document.
The problem is that I am seeing the $push variable being used a lot, but can't seem to get it working on my own project.
My Document
{
"_id": {
"$oid": "622dfd21f8976876e162c303"
},
"name": "testuser",
"password": "1234"
}
Lets say this is a document inside my collection users. I want to add an object that is called domains with some data inside that object like below:
"domains": {
"name": "example.com"
}
I have tried a bunch of different things, but they do not seem to work.
What I tried:
I have tried doing to like this:
$doc = array(
"domains" => array("name": "nu.nl")
);
$collection->insert($doc);
And like this:
$insertOneResult = $collection->updateOne(
{"name" : "testuser"},
'$push': {"domains": {"name": "example.com"}}
);
But they both do not work.
Can anyone help me with this problem or comment a link which would help me with this problem?
Thanks in advance!

You were really close!
db.users.update({
"name": "testuser"
},
{
"$push": {
"domains": {
"name": "example.com"
}
}
})
Try it on mongoplayground.net.
I haven't used php since the ancient gforge days, but my guess at using the php connector would be (corrections welcome!):
<?php
$collection = (new MongoDB\Client)->test->users;
$updateResult = $collection->updateOne(
['name' => 'testuser'],
['$push' => ['domains' => ['name' => 'example.com']]]
);
printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

Related

MongoDB how to find multiple documents using $match

I have a collection like this
{
"name": "Sai Darshan"
}
{
"name": "Sathya"
}
{
"name": "Richie"
}
I want to match the documents with the name "Sathya" and "Richie".
How can I achieve this using $match.
I currently tried this
$db = $this->dbMongo->selectDB("userData");
$collection = $db->selectCollection("userObject");
$aggregationFields = [
[
'$match' => [
'name'=> 'Sathya',
'name'=> 'Richie',
]
]
];
$cursor = $collection->aggregate($aggregationFields)->toArray();
Currently I am getting only the document
{
"name": "Richie"
}
I am expecting to fetch both documents i.e. the documents with the name "Sathya" and "Richie".
I expect to do this with $match itself because I have further pipelines I want to pass this data to.
Is there anyway I can achieve this?.
Any help is appreciated.
Thank you.
#nimrod serok answered in the comments, which is to use the $in operator.
What is probably happening in with the query in the description is that the driver is de-duplicating the name entry. So the query that the database receives only includes the filter for 'name'=> 'Richie'. You can see some reference to that here in the documentation, and javascript itself will also demonstrate this behavior:
> filter = { name: 'Sathya', name: 'Richie' };
{ name: 'Richie' }
>

how to append information to a document in mongo?

Background Information
I have the following data in my mongo database:
{ "_id" :
ObjectId("581c97b573df465d63af53ae"),
"ph" : "+17771111234",
"fax" : false,
"city" : "abd",
"department" : "",
"description" : "a test"
}
I am now writing a script that will loop through a CSV file that contains data that I need to append to the document. For example, the data might look like this:
+17771111234, 10:15, 12:15, test#yahoo.com
+17771111234, 1:00, 9:00, anothertest#yahoo.com
Ultimately I want to end up with a mongo document that looks like this:
{ "_id" :
ObjectId("581c97b573df465d63af53ae"),
"ph" : "+17771111234",
"fax" : false,
"city" : "abd",
"department" : "",
"description" : "a test",
"contact_locations": [
{
"stime": "10:15",
"etime": "12:15",
"email": "test#yahoo.com"
},
{
"stime": "1:00",
"etime": "9:00",
"email": "anothertest#yahoo.com"
},
]
}
Problem
The code I've written is actually creating new documents instead of appending to the existing ones. And actually, it's not even creating a new document per row in the CSV file... which I haven't debugged enough yet to really understand why.
Code
For each row in the csv file, I'm running the following logic
while(!$csv->eof() && ($row = $csv->fgetcsv()) && $row[0] !== null) {
//code that massages the $row into the way I need it to look.
$data_to_submit = array('contact_locations' => $row);
echo "proving that the record already exists...: <BR>";
$cursor = $contact_collection->find(array('phnum'=>$row[0]));
var_dump(iterator_to_array($cursor));
echo "now attempting to update it....<BR>";
// $cursor = $contact_collection->update(array('phnum'=>$row[0]), $data_to_submit, array('upsert'=>true));
$cursor = $contact_collection->insert(array('phnum'=>$row[0]), $data_to_submit);
echo "AFTER UPDATE <BR><BR>";
$cursor = $contact_collection->find(array('phnum'=>$row[0]));
var_dump(iterator_to_array($cursor));
}
}
Questions
Is there a way to "append" to documents? Or do I need to grab the existing document, save as an array, merge my contact locations array with the main document and then resave?
how can I query to see if the "contact_locations" object already exists inside a document?
Hi yes you can do it !
1st you need to find your document and push the new value you need :
use findAndModify and $addToSet :
$cursor = $contact_collection->findAndModify(
array("ph" => "+17771111234"),
array('$addToSet' =>
array(
"contact_locations" => array(
"stime"=> "10:15",
"etime"=> "12:15",
"email"=> "test#yahoo.com"
)
)
)
);
The best part is $addToSet wont add 2 time the same stuff so you will not have twice the same value :)
Here the docs https://docs.mongodb.com/manual/reference/operator/update/addToSet/
I'm not sure the exact syntax in PHP as I've never done it before but I'm currently doing the same thing in JS with MongoDB and $push is the method you're looking for. Also if I may be a bit nitpicky I recommend changing $contact_collection to $contact_locations as a variable name. Array variable names are usually plural and being more descriptive is always better. Also make sure you find the array in the MongoDB first that you want to append to and that you use the MongoDb "update" command

How to convert MongoDB BSONDocument to valid JSON in PHP?

I am using MongoDB with the PHP Library. I inserted a valid JSON document inside MongoDB using PHP. I am now retrieving the document using findOne and am getting a MongoDB\Model\BSONDocument object as a result. How do I get back my JSON document easily? Is there any inbuilt function or will I have to write logic to convert the BSONDocument to JSON?
I didn't see any answers here and I was having the same issue. I did some research and it appears that when you create a document of MongoDB\Model\BSONDocument there is a bsonSerialize() method. This method will return a stdClass Object which is really the PHP Array Class. According to documentation one can then convert from PHP to BSON and then to JSON.
This is crazy looking, but it works. Here is my example $accountResultDoc is of MongoDB\Model\BSONDocument type.
$json = MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($accountResultDoc))
Results
{
"_id": {
"$oid": "56e1d8c31d41c849fb292184"
},
"accountName": "Michael's Test Company",
"accountType": "Partner",
"subsidiary_id": {
"$oid": "563c3ffbaca6f518d80303ce"
},
"salesforceId": "WERWERWEr2",
"netsuiteExternalId": "56e1d8c31d41c849fb292184",
"suspendBilling": false,
"testAccount": false,
"serviceOrder_ids": null,
"invoice_ids": null
}
The BSONDocument object has a jsonSerialize method. Use that:
Example
{"_id" : 12345,
"filename" : "myfile",
"header" : {
"version" : 2,
"registry" : "test",
"serial" : 20080215,
"records" : 17806,
"startDate" : 19850701,
"endDate" : 20080214
},
}
$connect = new MongoDB\Client('mongodb://yourconnection');
$db = $connect->YourDB;
$collection = $db->YourCollection;
$test = $collection->findOne(array("_id"=>12345));
$data = $test->jsonSerialize();
echo $data->_id;
echo $data->filename;
Will output this:
12345
myfile
Another way would be:
json_encode( $bsonDoc->getArrayCopy() );
I had the same problem and this is how I accessed the values inside. This works with find.
foreach ($result as $entry) {
echo $entry['_id'], $entry['val1'], ['val2'];
}
Hope this helps someone.

How to get all children in firebase php?

What I'm trying to do is to get the all the child or users from firebase. Here is the JSON Data:
{
"users":{
"USER1":{
"data1": "123",
"data2": "123"
},
"USER2":{
"data1" : "456",
"data2" : "456"
}
}
}
Does anyone know how to get the child using firebasephp? I am using https://github.com/ktamas77/firebase-php this firebase php.
I'm not a PHP developer so this may not be 100% valid php but looking at the code you would do something possibly like this
$firebase = new Firebase('http://myfirebasename.firebaseio.com', TOKEN);
$users = $firebase->get('/users');
This should return you an array of the data at that endpoint.

Google Analytics API Authentication Speedup

I'm using a Google Analytics API Class in PHP made by Doug Tan to retrieve Analytics data from a specific profile.
Check the url here: http://code.google.com/intl/nl/apis/analytics/docs/gdata/gdataArticlesCode.html
When you create a new instance of the class you can add the profile id, your google account + password, a daterange and whatever dimensions and metrics you want to pick up from analytics.
For example i want to see how many people visited my website from different country's in 2009.
//make a new instance from the class
$ga = new GoogleAnalytics($email,$password);
//website profile example id
$ga->setProfile('ga:4329539');
//date range
$ga->setDateRange('2010-02-01','2010-03-08');
//array to receive data from metrics and dimensions
$array = $ga->getReport(
array('dimensions'=>('ga:country'),
'metrics'=>('ga:visits'),
'sort'=>'-ga:visits'
)
);
Now you know how this API class works, i'd like to adress my problem.
Speed. It takes alot of time to retrieve multiple types of data from the analytics database, especially if you're building different arrays with different metrics/dimensions. How can i speed up this process?
Is it possible to store all the possible data in a cache so i am able to retrieve the data without loading it over and over again?
You can load the data in a cache sure, precisely how/where the data is cached is entirely up to you. You can use anything from per-request caching (which will be pretty useless for this particular problem) to things like APC, memcached, a local database or even just saving the raw results to files. These will not make the actual retrieval of the data from Google any quicker of course.
On that note, it is likely (not having seen the code) that the requests over to Google are probably being executed sequentially. It is likely possible to extend the PHP class to allow requesting multiple sets of data from Google in parallel (e.g. with cURL Multi).
Faced the same problem and decided to use a cronjob and save the data in a .json file I can use for the display.
$globalTrendData = $client->runReport([
'property' => 'properties/' . $property_id,
'dateRanges' => [
new DateRange([
'start_date' => '20daysAgo',
'end_date' => 'yesterday',
]),
],
'dimensions' => [
new Dimension(['name' => 'pagePath',]),
new Dimension(['name' => 'pageTitle',]),
new Dimension(['name' => 'city',]),
new Dimension(['name' => 'sessionSource',]),
new Dimension(['name' => 'date',])
],
'metrics' => [
new Metric(['name' => 'screenPageViews',]),
new Metric(['name' => 'userEngagementDuration',]),
new Metric(['name' => 'activeUsers',]),
]
]);
foreach ($globalTrendData->getRows() as $key => $row) {
$saved['globalTrendData'][$key]['dimension']['pagePath'] = (array) $row->getDimensionValues()[0]->getValue() ;
$saved['globalTrendData'][$key]['dimension']['pageTitle'] = (array) $row->getDimensionValues()[1]->getValue() ;
$saved['globalTrendData'][$key]['dimension']['city'] = (array) $row->getDimensionValues()[2]->getValue() ;
$saved['globalTrendData'][$key]['dimension']['source'] = (array) $row->getDimensionValues()[3]->getValue() ;
$saved['globalTrendData'][$key]['dimension']['date'] = (array) $row->getDimensionValues()[4]->getValue() ;
$saved['globalTrendData'][$key]['metric']['screenPageViews'] = (array) $row->getMetricValues()[0]->getValue() ;
$saved['globalTrendData'][$key]['metric']['userEngagementDuration'] = (array) $row->getMetricValues()[1]->getValue() ;
$saved['globalTrendData'][$key]['metric']['activeUsers'] = (array) $row->getMetricValues()[2]->getValue() ;
}
file_put_contents($GLOBALS['serverPath'].'/monitoring/statistics.json',json_encode($saved, JSON_PRETTY_PRINT)) ;
Json file output exemple :
"globalTrendData": {
"0": {
"dimension": {
"pagePath": {
"0": "\/modeles-maison\/liste"
},
"pageTitle": {
"0": "Plans de maisons 100% personnalisables - adapt\u00e9s \u00e0 votre style et \u00e0 votre budget"
},
"city": {
"0": "(not set)"
},
"source": {
"0": "(direct)"
},
"date": {
"0": "20220128"
}
},
"metric": {
"screenPageViews": {
"0": "18"
},
"userEngagementDuration": {
"0": "152"
},
"activeUsers": {
"0": "1"
}
}
}
}

Categories