How to query with clauses on mongodb /PHP7? - php

It's my first contact to mongodb, I'm coding PHP7 with MONGODB database and don't know hown to query.
My query is working on mongo:
db.points.find(
{ coordenadas:
{ $geoWithin:
{ $centerSphere:
[ [ -23.010382,-43.476006 ] , 10 / 3963.2 ]
}
}
}
)
But I don't know how to coding it on PHP:
...
try {
$mongo = new MongoDB\Driver\Manager('mongodb://localhost:27017');
$filter = [
THE QUESTION IS HERE!
HOW TO CODING THE MONGO'S FIND
];
$query = new MongoDB\Driver\Query($filter);
$rows = $mongo->executeQuery(“points”, $query);
...

PHP code for the above query will be something like this :
$condition = array(
'coordenadas' => array(
'$geoWithin' => array(
'$centerSphere' =>
array(array( -23.010382,-43.476006 ), 10 / 3963.2)
)
)
);
If your db name is "my_db" and collection name "point_collection"
$collection = $mongo->my_db->point_collection;
$result = $collection->find($query);
You can refer the documentation for find();

Related

Mongodb php datetime filter not working properly

I use mongo db with php I need a last 1 hour data. I implement as like bellow.
{
"_id":{"$oid":"5ff42b30be00ec1eaf261db1"},
"logtype":"syslog",
"message":"Jan 4 06:51:56 4S-096 kernel: [70745743.387001] CPU7: Package temperature above threshold, cpu clock throttled (total events = 2955852254)",
"node_id":875,
"app_id":0,
"send_to_slack":1,
"created_date":{"$date":"2021-01-05T09:02:39.593Z"}
}
PHP CODE
$client = mongodb_connect();
$db = $client->$db_name;
$col = $db->selectCollection($collection_name);
$client->selectDatabase($db_name);
$criteria = array(
"created_date" => [$gte=> new \MongoDB\BSON\UTCDateTime(strtotime("-1 hour") * 1000)],
"logtype" => $logType,
"message" => trim($logdata),
"node_id" => $node_id,
);
$count = $col->count($criteria);
I need a count result. thanks in advance
I am not so familiar with PHP, but I think $client->$db_name is equal to $client->selectDatabase($db_name)
However -> does not work with variables, so $client->$db_name may fail.
Try this one:
$client = mongodb_connect();
$db = $client->selectDatabase($db_name);
$col = $db->selectCollection($collection_name);
$criteria = array(
"created_date" => [ '$gte' => new MongoDB\BSON\UTCDateTime(strtotime("-1 hour") * 1000)],
"logtype" => $logType,
"message" => trim($logdata),
"node_id" => $node_id,
);
$count = $col->count($criteria);
I never used strtotime, maybe you have to skip * 1000

Mongo mapper use aggregation framework

Can someone please point out my error, trying to sum a field(amount) using userId field?
https://fatfreeframework.com/3.6/mongo-mapper
Here is my code, this is returning me all documents matched with userId but not the sum.
$f3 = \Base::instance();
$mapper = new \DB\Mongo\Mapper($f3->get('MongoDB'),'transactions');
$filter = array('userId'=>'452');
$options = array(
array(
'group' => array(
'_id' => array('userId' => $userId),
'amount' => array('$sum' => 'amount')
)
)
);
$data = $mapper->find($filter, $options);
echo "<pre>";
print_r($data);
exit;
The mongo mapper uses the db.collection.group() method rather than the aggregation framework. Therefore you won't be able to call accumulators such as $sum.
Instead you must use the following syntax:
$group = [
'keys'=>['userId'=>1],
'initial'=>['sum'=>0],
'reduce'=>'function(obj,result){result.sum+=obj.amount;}',
'finalize'=>'function(result){}',
);
$data = $mapper->find($filter, ['group'=>$group]);

Yii2 MongoDB distinct count

How to get count distinct values from the collection using query?
Now I am using this solution:
$collection = Yii::$app->mongodb->getCollection('collection_name');
$result = $collection->distinct('field_id');
return count($result);
Collection example:
{
{a: 2},
{a: 2},
{b: 3},
{c: 4}
}
Result must be:
3
You can use the aggregation framework for this:
$collection = Yii::$app->mongodb->getCollection('collection_name');
$result = $collection->aggregate(
array('$group' => array(
'_id' => '$field_id'
)),
array('$group' => array(
'_id' => 1,
'count' => array( '$sum' => 1 )
))
);
Try this not tested but you can get your results, make some changes if exception occur.
use yii\mongodb\Query;
$query = new Query;
$count = $query->from('collection_name')->distinct('field_id')->count();
More detail

select by time from mongodb by using php error

I was trying to query from mongodb using php, my database looks like this
{
"_id" : ObjectId("55892817d4302e281b8b4567"),
"subject" : "Report",
"createdAt" : ISODate("2015-06-23T09:34:15Z"),
"processedAt" : ISODate("2015-07-23T09:34:15Z"),
"testNumber" : 10
}
and my query is:
$procInMins = 60;
$anchor = new \DateTime('now', new \DateTimeZone('UTC')); // now
$anchor->sub(new \DateInterval('PT' . $procInMins . 'M'));
$query = array( "subject" => "Report", "processedAt" => array( '$gt' => $anchor));
$cursor = $collection->find($query);
and this returns a cursor whose count is 0, but i also tried
$query = array( "subject" => "ProcessOverflowSmsLogCommandTest Report", "testNumber" => array('$gt'=>3) );
in this case i compare the testNumber field and it returns 1 result, which is correct. So i think there's something wrong with the date, but I have no idea how to fix this. Thanks

Get distinct values and case insensitive with MongoDb

Is it possible to get distinct values and be case insensitive? I found a couple people saying to use the aggregate function but I would keep getting errors like: exception: field path references must be prefixed with a '$' ('Classification'.
public function getDistinctValues($cid, $table, $column)
{
$mongo = new MongoClient();
$db = $mongo->leadworks;
$collection = new MongoCollection($db, $table);
//$result = $collection->distinct($column);
$result = $collection->aggregate(array(
array(
'$unwind' => $column,
),
array(
'$group' => array(
'_id' => array(
'$toLower' => array(
$column,
),
),
),
),
));
return $result;
}
This is how my document looks:
{
_id:2065565,
Date:new Date(1411732940000),
Email:"email#email.com",
Other - Industry:null,
Other - Job Duties:null,
First Name:"Test Name",
Last Name:"Test Last Name",
Title:"engineer",
Company:"Company Name Here",
Country:"UNITED STATES",
State:"MI",
Zipcode:"48071-1514",
Phone number:"777-777-7777",
Company type:"Systems integration",
}
I'm specifically trying to get distinct values for Company and ignore case.

Categories