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 :)
Related
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 want to create a ZF3 \Zend\Db\Sql\Select object where table is pgsql expression:
generate_series('2017-01-01'::date, '2017-02-01'::date, '1 day'::interval)
but if I pass expression as \Zend\Db\Sql\Expression object, like this:
$select = new \Zend\Db\Sql\Select();
$select->from(['dd' => new \Zend\Db\Sql\Expression("generate_series('2017-01-01'::date, '2017-02-01'::date, '1 day'::interval)")]);
I'm getting following error:
Catchable fatal error: Object of class Zend\Db\Sql\Expression could not be converted to string
but if I pass my expression as string, it's getting automatically wrapped and looks like this:
SELECT "dd".* FROM "generate_series('2017-01-01'::date, '2017-02-01'::date, '1 day'::interval)" AS "dd"
which is of course wrong. Is it possible to achieve without overwriting ZF3 Select class?
Select::form() method takes table name as its argument. You may try this way:
$select = new \Zend\Db\Sql\Select();
$select->columns(['AliasName' => new \Zend\Db\Sql\Expression("YourExpression")]);
This would produce following query:
SELECT YourExpression AS "AliasName"
Updated
The working example of the above method is down here. First, create an instance of database adapter providing database information. In this case, we are using PDO driver for Postgresql.
$adapter = new \Zend\Db\Adapter\Adapter([
'driver' => 'Pdo_Pgsql',
'database' => 'YourDatabaseName',
'username' => 'YourDatabaseUsername',
'password' => 'PasswordForDatabase',
]);
Next up, we are going to create an another instance of Sql::class from zend-db component. It is not mandatory if you are using TableGateway::class in your controller action.
$sql = new \Zend\Db\Sql\Sql($adapter);
Now here is the one you want, the Select object, which we are creating from the previous Sql object. Here we are also querying through zend-db's Expression::class to generate some date series.
$select = $sql->select();
$select->columns(["dd" => new \Zend\Db\Sql\Expression("generate_series('2007-02-01'::timestamp, '2007-03-01'::timestamp, '1 day'::interval)")]);
If we output the sql as string we would then get as the following
SELECT generate_series('2007-02-01'::timestamp, '2007-03-01'::timestamp, '1 day'::interval) AS "dd"
As we are using PDO driver for postgresql, we would prepare the statement at the moment, and finally execute the sql.
$statement = $sql->prepareStatementForSqlObject($select);
$results = $statement->execute();
If we output the results we fetched we would then get a series of dates as the following
foreach ($results as $row) {
print $row['dd'] ."</br>";
}
// Outputs
2007-02-01 00:00:00
2007-02-02 00:00:00
2007-02-03 00:00:00
2007-02-04 00:00:00
...
Hope this would help you!
For start, I have to say I am new to mongo (3.2). I am using mongo-odm-aggregation-bundle for php framework Symfony (2.8.4). I want to get sums of some fields restricted by dates.
So far, I managed to get sums for all records:
$expr = new \Solution\MongoAggregation\Pipeline\Operators\Expr;
$aq = $this->manager->getCollection('AppBundle:UserDaySums')->createAggregateQuery()->group([
'_id' => 'client.$id',
'total' => $expr->sum('$aSum'),
])
Now, I'd like to restrict this query by dateFrom,dateTo and userId. I am not sure, how to do it. I know, I should probably use match function, but I don't know how. Or is there some better solution?
Thanks for replies!
KP
Yes, you can use the match function. For example, the following assumes you have the date variables for use in the query:
$expr = new \Solution\MongoAggregation\Pipeline\Operators\Expr;
$aq = $this->manager->getCollection('AppBundle:UserDaySums')->createAggregateQuery();
$dateFrom = new MongoDate(strtotime('-2 days'));
$dateTo = new MongoDate();
$userId = 'Xsgy62js0lb';
$result = $aq->match(['dateFrom'=>$dateFrom, 'dateTo'=>$dateTo, 'userId'=>$userId ])
->group(['_id'=>'client.$id', 'total'=>$expr->sum('$aSum') ])
->getQuery()->aggregate();
In my case, match() was somewhat tricky on a MongoId object.
This didn't work for me:
$userMongoId = "57321c7a2977f8de306ef648";
$aq ->match([ 'user.$id' => $expr->eq($userMongoId) ])
This worked:
$aq ->match([ 'user' => new \MongoId($userMongoId) ])
Tested on Symfony 3 with the SolutionMongoAggregationBundle, MongoDB version 3.2.6.
I essentially want to search the database using an array of barcodes. Here is my query if I only have one barcode:
$q = new CDbCriteria(array(
'condition' => '"barcode" = :barcode',
'params' => array(':barcode' => $this->barcode),
));
I am trying to modify this query so that I query an array of barcodes. It would be a fairly standard array, something like ['Barcode1','Barcode2', 'Barcode3'].
How can I modify this query I have to instead return the results for Barcode1 OR Barcode2 OR Barcode3?
You need to add an inCondition
http://www.yiiframework.com/doc/api/1.1/CDbCriteria#addInCondition-detail
something like this
$q = new CDbCriteria();
$q->addInCondition("barcode",array("value1","value2"...),"AND");
I'm using the mongoDB to store the log of user. In my real-time report, I need to count the distinct user of the table in a specific type. In the beginning, it runs fast, but it become slower when the table becomes bigger.
Here is the code I used:
$connection = new MongoClient();
$result = $collection->distinct('user', array('type' => $type, 'ctime' => array('$gte' => $start)));
$total = count($result);
$total is the total number of unique user
Can anyone suggest me how to improve the query to get the better performance?
Many thanks.
use $collection->ensureIndex(array('user' => 1)); to create index on user field.