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
Related
In MongoDB PHP, is it possible to update the value of a field using the value from another field?
The below Mongo Shell Command is working fine. Value of a field "product_name" is updating to the field "product_name_copy".
db.products.update(
{},
[{ $set: {
"product_name_copy": "$product_name"
}}],
{ multi: true }
)
But, While Am using this code in PHP,
PHP code :
$where = array();
$update = array('$set' => array("product_name_copy" => "$product_name"));
$options = array("multi" => true);
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->update($where,$update,$options);
$updated = $mongo->executeBulkWrite("$db_name.products", $bulkWrite);
Am getting this error
Notice: Undefined variable: product_name in
C:\xampp\htdocs\mongo\mongo-update.php on line 10
If I used single quotes instead of double quotes,
$update = array('$set' => array("product_name_copy" => '$product_name'));
the same value $product_name is updating to the field "product_name_copy" like below.
{
"_id" : ObjectId("602a291f0406011059006c15"),
"product_id" : 15,
"product_name" : "Test Product",
"product_name_copy" : "$product_name"
}
Anyone know the solution for this problem.?
Finally I found the solution.
We need to put '$set' array into another one array for field value update.
PHP Code :
$where = array();
$update = array(array('$set' => array("product_name_copy" => '$product_name')));
$options = array("multi" => true);
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->update($where,$update,$options);
$updated = $mongo->executeBulkWrite("$db_name.products", $bulkWrite);
Output of the above code is
{
"_id" : ObjectId("602a291f0406011059006c15"),
"product_id" : 15,
"product_name" : "Test Product",
"product_name_copy" : "Test Product"
}
This is what I exactly wanted.
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
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();
I want to display all documents (select *) with sub-documents in PHP.
I know how to query all find() but I have no idea how to do it when I have sub-documents. I don't know if there's something like find() or I need to make loops fo every sub-documents that I'd have.
This would be the code
$mongodatabase->insertOne(
['name' => 'Alex',
'surname' => 'Turner',
'country' => 'England',
'birth' => array(
'day' => 6,
'month' => 'january',
'year' => 1986
),
]);
Something easy, just to learn. When I try a var_dump of day I get Undefined index and NULL.
$client = new MongoDB\client;
$db = $client->database;
$mongodatabase = $db->document;
$document = $mongodatabase->find();
foreach ($document as $doc) {
var_dump($doc->day);
}
However, I'd like to query all.
Use $exists - It helps us in identifying the elements which are not empty
db.collection_name.find({
"birth.day" : {
$exists : true
}
});
If you need to check not null and empty, then we need to use $type together with $exists, $type can be passed with different values and 10 is for null check
db.collection_name.find({
"birth.day" : {
$not : { $type : 10 },
$exists : true
}
});
when u find the exactly data from mongoldb u can use the shelter to limit the field
eg:
db.xxxxx.find(
{'status':'DELIVRD'}
);
I have a mongodb table with unique index on "userID"
$collection = $db->databsename->collectionName;
$userId = 1;
$lastTimeOnline = date("Y-m-d h:i:s");
echo $lastTimeOnline; // output : 2016-02-22 05:20:53
$doc = array(
"userID" => $userId,
"lastTimeOnline" => $lastTimeOnline,
"displayName" => ''
);
$a = $collection->insert($doc); // This will successfully insert
sleep(1);
$lastTimeOnline = date("Y-m-d h:i:s");
echo "\n".$lastTimeOnline;// output : 2016-02-22 05:20:54
$lastTimeOnline = date("Y-m-d h:i:s");
$doc = array(
"userID" => $userId,
"lastTimeOnline" => $lastTimeOnline,
"displayName" => ''
);
$a = $collection->insert($doc); // This will pass but not insert any thing
var_dump($db->lastError());
As expected last line will yield below error
array(5) {
'connectionId' =>
int(101)
'err' =>
string(88) "E11000 duplicate key error collection: databsename.collectionName index: userID_1 dup key: { : 1 }"
'code' =>
int(11000)
'n' =>
int(0)
'ok' =>
double(1)
}
Requirement
I need 2nd insert to replace first. i.e "2016-02-22 05:20:54" should replace "2016-02-22 05:20:53".
Solution:
Do i need to check if error exists then update the record or a better sol is available?