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))));
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!
I current have a database with the following document:
{"_id":"5d9bd9429303fc05f0651ff2",
"userID":"2",
"email":"admin#admin.com",
"password":"admin",
"dob":"1990-12-06",
"firstName":"AdminFirst",
"lastName":"AdminLast",
"screenName":"The Admin",
"gender":"m",
"status":"status",
"location":"location",
"visibility":"e",
"friends":[""],
"friendRequests":[""]}
I am connecting to the MongoDB through PHP, with the following code:
//connect to the client
$client = new MongoDB\Client("mongodb://localhost:27017");
//Connect to the specific collection
$collection = $client->FBLite->Users;
//Specific user document, stored in session.
$user = $_SESSION['currentDocument'];
I am trying to $push a string value into the "friends" array of one of my documents. What would be the correct way to do this via PHP?
I have tried:
$addFriend = update(array('$push'=> array("friends","4"));)
and:
$collection->update(['userID'] => 2, '')
However neither of these will work, and PHP will not throw any errors for me to read.
This was done with the following:
$collection->updateOne(
['userID' => '2'],
['$push' => ['friends' => '55']]
);
Will push the value "55" to the object with userID '2'
I try NoSQL.
I know how delete by id
$criteria = array(
'_id' => new MongoId('5277aeb6b28fada80a00002b'),
);
$users->remove($criteria);
but how to delete if you new for example value, like "name"="John"
You have to do absolutely the same thing as you have done with _id field:
$users->remove(array(
'name' => 'John'
));
You can always look at mongodb php documentation to find how to transform mongodb shell code to php.
I don't now how it is represented in PHP, but in Scala you would do something like this:
val criteria = MongoDBObject("name" -> "John")
coll.remove(criteria)
Usually when I search for one related ID I do it like this:
$thisSearch = $collection->find(array(
'relatedMongoID' => new MongoId($mongoIDfromSomewhereElse)
));
How would I do it if I wanted to do something like this:
$mongoIdArray = array($mongoIDfromSomewhereElseOne, $mongoIDfromSomewhereElseTwo, $mongoIDfromSomewhereElseThree);
$thisSearch = $collection->find(array(
'relatedMongoID' => array( '$in' => new MongoId(mongoIdArray)
)));
I've tried it with and without the new MongoId(), i've even tried this with no luck.
foreach($mongoIdArray as $seprateIds){
$newMongoString .= new MongoId($seprateIds).', ';
}
$mongoIdArray = explode(',', $newMongoString).'0';
how do I search '$in' "_id" when you need to have the new MongoID() ran on each _id?
Hmm your rtying to do it the SQL way:
foreach($mongoIdArray as $seprateIds){
$newMongoString .= new MongoId($seprateIds).', ';
}
$mongoIdArray = explode(',', $newMongoString).'0';
Instead try:
$_ids = array();
foreach($mongoIdArray as $seprateIds){
$_ids[] = $serprateIds instanceof MongoId ? $seprateIds : new MongoId($seprateIds);
}
$thisSearch = $collection->find(array(
'relatedMongoID' => array( '$in' => $_ids)
));
That should produce a list of ObjectIds that can be used to search that field - relatedMongoID.
This is what I am doing
Basically, as shown in the documentation ( https://docs.mongodb.org/v3.0/reference/operator/query/in/ ) the $in operator for MongoDB in fact takes an array so you need to replicate this structure in PHP since the PHP driver is a 1-1 with the documentation on most fronts (except in some areas where you need to use an additional object, for example: MongoRegex)
Now, all _ids in MongoDB are in fact ObjectIds (unless you changed your structure) so what you need to do to complete this query is make an array of ObjectIds. The ObjectId in PHP is MongoId ( http://php.net/manual/en/class.mongoid.php )
So you need to make an array of MongoIds.
First, I walk through the array (could be done with array_walk) changing the values of each array element to a MongoId with the old value encapsulated in that object:
foreach($mongoIdArray as $seprateIds){
$_ids[] = $serprateIds instanceof MongoId ? $seprateIds : new MongoId($seprateIds);
}
I use a ternary operator here to see if the value is already a MongoId encapsulated value, and if not encapsulate it.
Then I add this new array to the query object to form the $in query array as shown in the main MongoDB documentation:
$thisSearch = $collection->find(array(
'relatedMongoID' => array( '$in' => $_ids)
));
So now when the query is sent to the server it forms a structure similar to:
{relatedMongoId: {$in: [ObjectId(''), ObjectId('')]}}
Which will return results.
Well... I came across the same issue and the solution might not be relevant anymore since the API might have changed. I solved this one with:
$ids = [
new \MongoDB\BSON\ObjectId('5ae0cc7bf3dd2b8bad1f71e2'),
new \MongoDB\BSON\ObjectId('5ae0cc7cf3dd2b8bae5aaf33'),
];
$collection->find([
'_id' => ['$in' => $_ids],
]);
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