SOLVED
To view the data, I was doing a var_dump on the cursor and you have to loop through the cursor first to var_dump it.
foreach($user_images as $image) {
var_dump($image)
}
Can find out more about this at:
http://php.net/manual/en/class.mongocursor.php
/SOLVED
I have a collection called 'user_image' in my MongoDB. I am using PHP 5.3 with mongoDB db v2.0.5, pdfile version 4.5. I have this setup in my XAMPP. I am simply trying to find all documents in the collection. When I run the information below, nothing returns back even though I can confirm in the terminal running the db.user_image.find() that it returns results.
$m = new Mongo();
$db = $m->selectDB('dev_app');
$collection = new MongoCollection($db, 'user_image');
$collection->find();
If I change the query to simply use findOne by a user_uuid I get a result! Example below:
$collection->findOne(array('user_uuid' => 'de977803-f198-416a-8806-acbc1fa3f718'));
Here is an example document in the collection user_image:
{
"_id" : ObjectId("500c3f13ab8692ced0d9df6f"),
"user_uuid" : "de977803-f198-416a-8806-acbc1fa3f718",
"image_name" : "4a5e286e101429da0a3c3a576ffa4878.jpg",
"image_url" : "/uploaded_files/files/4a5e286e101429da0a3c3a576ffa4878.jpg",
"sm_thumb_url" : "/uploaded_files/thumbnails/4a5e286e101429da0a3c3a576ffa4878.jpg",
"md_thumb_url" : "/uploaded_files/files/4a5e286e101429da0a3c3a576ffa4878.jpg",
"lg_thumb_url" : "/uploaded_files/files/4a5e286e101429da0a3c3a576ffa4878.jpg",
"status" : "A",
"created" : ISODate("2012-07-22T17:57:36.835Z"),
"modified" : ISODate("2012-07-22T17:57:36.835Z"),
"created_by_uuid" : "de977803-f198-416a-8806-acbc1fa3f718",
"modified_by_uuid" : "de977803-f198-416a-8806-acbc1fa3f718"
}
What am I missing in the find query? Can anyone help me? Thanks.
Cursor Object is a 'key' here
The $cursor = $collection->find(); find() method will return a Cursor Object.
Now you can use toArray() method to get your data.
$dataArray = $cursor->toArray(); Simple as that. Or use foreach to get documents one by one. Ps. FindOne() which returns an array.
https://www.php.net/manual/en/class.mongodb-driver-cursor.php
Related
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!
In my MongoDB, I have stored value as below,
{
"_id" : ObjectId("5bed3f5019f0431be000412b"),
"reference" : "SL2PR01MB2745E4160158C08C4B7A367285C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com,SL2PR01MB274333160158C08C4B7A367285C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com",
"email_thread_id" : NumberInt(5)
}
{
"_id" : ObjectId("5bed3f5019f0431be000412b"),
"reference" : "SL2PR01MB2745E4160158C08C4B7A364444C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com",
"email_thread_id" : NumberInt(6)
}
My search keyword is:
"SL2PR01MB2745E4160158C08C4B7A364444C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com"
Which is match with second array from above JSON.
This is my query,
$referanceId= "SL2PR01MB2745E4160158C08C4B7A364444C30#SL2PR01MB2745.apcprd01.prod.exchangelabs.com";
$mailExists = DB::connection('mongodb')->collection('email_message')
->select('email_thread_id');
if ($referanceId) {
$mailExists->whereRaw("find_in_set(".$referanceId.", reference)");
}
$query = $mailExists->first();
But it gives me error like below:
ServerException in Find.php line 299:
$or/$and/$nor entries need to be full objects
Please help me to resolve this issue. Thank you.
You can do this easier with the laravel where method, this will do the comparison you want, and also make your code better readable.
You can use the following query to accomplish this:
DB::connection('mongodb')->collection('email_message')
->where("reference", $referanceId)->first();
If your value contains multiple reference id's as a string you can use:
$regexQuery = '/.*'.$referanceId.'.*/';
DB::connection('mongodb')->collection('email_message')
->where("reference", 'regexp', $regexQuery)->first();
This will match the referenceId in any position in the string.
As #hetalgotel mentioned in the comments another query for this is:
$mailExists->where("reference", 'like', "%$referanceId%")
This one produced the expected result in this scenario
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 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 want to get the max id value on a collection.
How do I convert the mongoDb query:
db.tweets.find({},{id:1}).sort({id:-1}).limit(1)
to Mongo Query Language Statement using PHP?
I'm trying
$db->tweets->find(
array(),
array("id"=>1)
)->sort(array("id"=> -1))->limit(1);
but that doesn't work.
I checked this and it works for me:
$val = $db->myCollection->find(array(), array('_id' => 1))->sort(array('_id' => -1))->limit(1);
The error in your code is that it should be "_id" and not "id". Also, I hope $db->tweets is a MongoCollection object and you have ensured this. Hope this helps.