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'
Related
I am using php7 and MongoDB new driver manager in my project. I want one query which is same mysql LIKE query
Below are my search feild in my MongoDB collection:-
fullAddress: 1013 BISMARCK ROAD PUNTA GORDA FL 33983 US
I want one query to find all records who belongs to "33983" value.
Below are my code:-
new MongoDB\BSON\Regex("^33983", 'i')
but its not working it s showing no records found error but this result set actully present in database i want LIKE query which is same in mysql Like query ('%LIKE%').
Here is an updated Query with like query using MongoDB. Here is full documentation https://docs.mongodb.com/manual/reference/operator/query/regex/
$requestlist = '33983';
$options = ['limit' => 10, 'skip' => 0, 'sort' => ['listprice.listprice' => 1]];
$dataSend = array('listingStatus' => 'Active');
$nameCondition = []; $nameCondition[] = array('fullAddress' => new MongoDB\BSON\Regex($requestlist));
$nameCondition[] = array('mlsNumber' => new MongoDB\BSON\Regex($requestlist));
$dataSend['$or'] = $nameCondition;
$query = new MongoDB\Driver\Query($dataSend,$options);
$rows = $manager->executeQuery("TableName.Collection", $query);
Hope this will help :)
I use this code in the MongoDB PHP driver to get all documents in the database
$result = $collection->find();
foreach ($result as $doc) {
print_r($doc);
}
However, when adding a limit to it, it doesn't work anymore: no documents get printed anymore:
$result = $collection->find()->limit(10);
foreach ($result as $doc) {
print_r($doc);
}
There are certainly enough documents in the database. I cannot figure out what the problem with this is.
I have fixed the problem by taking a look at the source of the beta version. The documentation only appeared to be for the legacy mongo extension and not the newer mongodb extension.
The error logs showed this: Call to undefined method MongoDB\\Driver\\Cursor::addOption(). I checked out the documentation and concluded the function should have worked because it said (PECL mongo >=0.9.0). Note the missing db after mongo.
I fixed it by doing:
$collection->find([], [ 'limit' => 2 ]);, providing an empty filters array and adding my options in another array afterwards.
I am trying to describe with example for new php mongodb driver. showing in example skip,limit,Fields slection
require 'vendor/autoload.php'; // include Composer's autoloader
$client = new MongoDB\Client("mongodb://localhost:27017");
// SELECT * FROM YOUR_TABLE_NAME ;
// db.YOUR_COLLECTION_NAME.find({});
$result = $clinet->YOUR_DB_NAME->YOUR_COLLECTION_NAME->find(array());
//SELECT * from YOUR_TABLE_NAME WHERE YOUR_COLUMN = "A"
// db.YOUR_COLLECTION_NAME.find({{ YOUR_FIELD: "A" }});
$result = $clinet->YOUR_DB_NAME->YOUR_COLLECTION_NAME->find(array('YOUR_FIELD'=>'A'));
//Return the Specified Fields and the _id Field Only
//SELECT _id, item,status YOUR_TABLE_NAME from inventory WHERE status = "A"
//db.YOUR_COLLECTION_NAME.find( { status: "A" }, { item: 1, status: 1 } )
$result = $clinet->YOUR_DB_NAME->YOUR_COLLECTION_NAME->find(array('status'=>'A'),array('projection' =>array('item'=>TRUE,'status' => TRUE)));
//Suppress _id Field
//SELECT item, status from YOUR_TABLE_NAME WHERE status = "A"
//db.YOUR_COLLECTION_NAME.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
$result = $clinet->YOUR_DB_NAME->YOUR_COLLECTION_NAME->find(array('status'=>'A'),array('projection' =>array('item'=>TRUE,'status' => TRUE,'_id'=>FALSE)));
//SELECT * FROM YOUR_TABLE_NAME LIMIT 10
//db.YOUR_COLLECTION_NAME.find({}).limit(10);
$result = $clinet->YOUR_DB_NAME->YOUR_COLLECTION_NAME->find(array(),array('limit'=>10));
//SELECT * FROM YOUR_TABLE_NAME LIMIT 5,10
//db.YOUR_COLLECTION_NAME.find({}).skip(5).limit(10)
$result = $clinet->YOUR_DB_NAME->YOUR_COLLECTION_NAME->find(array(),array('skip'=>5,'limit'=>10));
//Suppress _id Field
//SELECT item, status from YOUR_TABLE_NAME WHERE status = "A" LIMIT 5,10;
//db.YOUR_COLLECTION_NAME.find( { status: "A" }, { item: 1, status: 1, _id: 0 } ).skip(5).limit(10);
$result = $clinet->YOUR_DB_NAME->YOUR_COLLECTION_NAME->find(array('status'=>'A'),array('projection' =>array('item'=>TRUE,'status' => TRUE,'_id'=>FALSE),'skip'=>5,'limit'=>10));
foreach ($result as $entry){
echo "<pre>";
print_r($entry);
echo "</pre>";
}
As a solution to your above mentioned problem please try executing following code snippet.
$result = $collection->find();
$result->limit(10);
foreach ($result as $doc) {
print_r($doc);
}
I had the same issue. There are a lot of code examples using $result = $collection->find()->limit(10);
It turns out, that while this was totally valid for the original version of the MongoDB PHP driver, there is a new version of that very same driver. The original driver is now considered "The Legacy Driver".
Here is one example, how the "old" driver was supposed to be used:
<?php
$m = new MongoClient;
// Select 'demo' database and 'example' collection
$collection = $m->demo->example;
// Create the cursor
$cursor = $collection->find();
At this moment, although a cursor object had been created, the query had not yet executed (i.e. it was not sent to the server). The query would only be executed by starting iteration with foreach ( $cursor as $result ) or calling $cursor->rewind(). This gives you the chance to configure the cursor's query with sort(), limit(), and skip() before it is executed by the server:
// Add sort, and limit
$cursor->sort( [ 'name' => 1 ] )->limit( 40 )
In the new driver, as soon as you have a \MongoDB\Driver\Cursor object, it has already been processed by the server. Because sort (and limit and skip) parameters need to be sent to the server before the query is executed, you can not retroactively call them on an existing Cursor object.
This is the reason, why there is no limit() method anymore, as there used to be. Also, the accepted answer is correct. I want to give a more elaborate example:
$filter = [
'author' => 'rambo',
'views' => [
'$gte' => 100,
],
];
$options = [
/* Return the documents in descending order of searchPage */
'sort' => [
'searchPage' => -1
],
/* Limit to 2 */
'limit' => 2,
/* close the cursor after the first batch */
'singleBatch' => true,
];
$cursor = $collection->find($filter, $options);
I tried following the basic example of solr in php from the official docs (http://www.php.net/manual/en/book.solr.php).
I wanted to write a function that simply return the solr index.
For example, consider the following code:
$options = array( 'hostname' => SOLR_SERVER_HOSTNAME );
$client = new SolrClient($options);
$doc = new SolrInputDocument();
$doc->addField('id', 12345);
$doc->addField('title', 'Stack Overflow');
$client->addDocument($doc);
$client->commit();
This works perfectly. But, lets say I wanted to write a function that simply returns me the solr index. For example:
function get_index(){
$index = //something here
...
return $index;
}
How can I do this? Is this possible? I'm new to solr and I'm using the PECL Solr client.(http://www.php.net/manual/en/book.solr.php)
Please refer to examples #4 & #5 from the Examples page for the Solr PECL client. Then you can build a query that searches across and returns all fields, like the following:
$options = array (
'hostname' => SOLR_SERVER_HOSTNAME,
'port' => SOLR_SERVER_PORT);
$client = new SolrClient($options);
$query = new SolrQuery();
$query->setQuery('*:*'); // *:* means search all fields for all values.
$query->setStart(0);
$query->setRows(100000); //very large to ensure all rows are returned.
$query->addField('*'); // * will return all fields
$query_response = $client->query($query);
$query_response->setParseMode(SolrQueryResponse::PARSE_SOLR_DOC);
$response = $query_response->getResponse();
print_r($response);
For more details on querying Solr and the options that you can use, please refer to the following:
Searching in Solr
Solr Query Syntax & Common Query Parameters
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],
]);
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))));