MongoDB PHP Date - mongodb

In my database I have a document like this.
{
"_id" : ObjectId("5465508f453c9446d228b225"),
"category" : "animals",
"lastLocation" : "Wilpattu",
"lastSeenDate" : "2013-05-26",
"company" : "53fd9a3204ac58132377f807"
}
I want to check if the given date is in between two date ranges. I am using Codeigniter for front end development. In the model class I have written,
$connection =$this->Dbconnect->GetMongoCon();
$database = $connection->etsp;
$collection = $database->trackedObjects;
$start = $AnimalArray['fyear']. '-'.$AnimalArray['fmonth'].'-'.$AnimalArray['fday'];
$end = $AnimalArray['lyear']. '-'.$AnimalArray['lmonth'].'-'.$AnimalArray['lday'];
$searchCriteria = array(
'company' => $AnimalArray["Company"],
'lastSeenDate' =>array('$gt' => $start1, '$lte' => $end1)
);
$ReturnAnimalArray=$collection->find($searchCriteria);
But I can't query the date. From internet I have tried converting date into mongodb format.
$start1 = new MongoDate(strtotime(date($start )));
$end1 = new MongoDate(strtotime(date($end)));
But that also did not work. Any hint will be highly appreciated.

lastSeenDate is not MongodbDate format, may be you should like do this:
$js = "function() {
return this.lastSeenDate > '2013-02-18' && this.lastSeenDate <= '2014-09-28';
}";
$collection->find(array('$where' => $js));

Related

can't get data from mongodb using perl (get undefined value)

I am trying to get data from mongodb using perl, but I get undefined value for variable $people
my $client = MongoDB::MongoClient->new(host =>
'mongodb://xxx.xxx.xxx.xxx',port=>27017, username => 'xxxx',
password => 'xxxx');
my $db = $client->get_database("xxx");
my $collection = $db->get_collection("xxx");
my $people = $collection->find_one({"transactionid" => $id});
while (my $p = $people->next) {
print Dumper $p;
}
and I want to get this data :
{
"_id" : ObjectId("5c453500e2fb4adc98e9fa84"),
"transactionid" : NumberLong(45282),
"transactionbillerid" : NumberLong(43137),
"requesttime" : ISODate("2019-01-21T02:57:04.923Z"),
"requestmessage" : "xxxxxxxx",
"responsetime" : ISODate("2019-01-21T02:57:05.236Z"),
"responsemessage" : "xxx"
}
any suggestions, is there something wrong with my code ?
I think you're misunderstanding the value returned by find_one(). There's a big clue in the name, but find_one() returns a single record, not an iterator.
Obviously, I don't have access to your data, so I can't confirm this, but I expect you'll get what you want by running this code:
my $client = MongoDB::MongoClient->new(
host => 'mongodb://xxx.xxx.xxx.xxx',
port => 27017,
username => 'xxxx',
password => 'xxxx',
);
my $db = $client->get_database("xxx");
my $collection = $db->get_collection("xxx");
my $person = $collection->find_one({"transactionid" => $id});
print Dumper $person;

MongoDB Raw query to select documents which are in given datetime period

I want to select documents which are in user given date time period like between :
$from_date : "2017-01-07 09:08:59" To `$to_date : "2017-08-09 09:08:59"`
I'm using laravel framework and jenssegers/laravel-mongodb mongodb driver to run my query, And this is my Raw query :
$normal_banners = BannerView::raw(function ($collection) use ($id, $from_date, $to_date) {
$conditions = [
["camp_id" => ['$eq' => $id]],
['$or' => [
['seat_target_status' => ['$eq' => true]],
['seat_target_status' => ['$eq' => false]]
]],
['camp_target_status' => ['$eq' => false]],
];
if ($from_date) {
$conditions[] = ['created_at' => ['$gte' => $from_date]];
}
return $collection->aggregate([
['$match' => ['$and' => $conditions]],
]);
})->count();
But my problem is that it returns 0 as result; while there are 16 documents in this time period.
I've tried this method to get the count of them but still 0 result :
$normal_banners = BannerView::Where('camp_id', $id)
->where(function ($query) {$query->where('seat_target_status', true)->orWhere('seat_target_status', false);
})
->where('camp_target_status', false)
->where("created_at", ">=", $from_date)
->count();
FYI : I've converted datetime of input to ISODate Which is the mongodb datatype for created_at field.
$Fromdatetime = $request->input('from_date');
$from_date = new DateTime($Fromdatetime);
$from_date = $from_date->format(DateTime::ISO8601);
mongodb field data type is :
"updated_at": ISODate("2017-04-10T09:35:58.641Z"),
"created_at": ISODate("2017-04-10T09:35:58.641Z")
My input data type is : "2017-01-07T09:08:59+0000"
Any suggestion ?
You have to "put in braces" orWhere function and in your raw query you are testing $to_date with updated_at column, but in Eloquent code you are making between with created_at column
$targeted_banners = BannerView::Where('camp_id', $id)
->where(function($query){$query->where('seat_target_status', true)->orWhere('seat_target_status', false);})
->where('camp_target_status', false)
->where("created_at", ">=" $from_date)
->where("updated_at", "<=", $to_date)
->count();
I've solved this problem using Carbon::createDateFrom method, it create a UTC date time base on my input :
Inputs :
{
"from_date": "2017-03-10",
"to_date": "2017-04-09"
}
Converting input dates :
$from_date_arr = explode("-",$request->input('from_date'));
$from_date = Carbon::createFromDate($from_date_arr[0],$from_date_arr[1],$from_date_arr[2]);
$to_date_arr = explode("-",$request->input('to_date'));
$to_date = Carbon::createFromDate($to_date_arr[0],$to_date_arr[1],$to_date_arr[2]);
And This is the query I run which worked :
$normal_banners = BannerView::Where('camp_id', $id)
->where(function ($query) {$query->where('seat_target_status', true)->orWhere('seat_target_status', false);
})
->where('camp_target_status', false)
->where("created_at", ">=",$from_date)
->where("created_at", "<=",$to_date)
->count();
There is a strange problem still with jessenger driver which whereBetween is not working and we should use two where clause to make it work.
Hope solves others problem.

Query builder mongodb index datetime

I'm looking to execute custome query with doctrine odm in fulltext search and datetime range
Indexes are already generated on mongodb
Here is my code :
$search = $dm->createQueryBuilder('VideoBundle:Video');
if (isset($_POST['date']))
{
$from = new \DateTime($_POST['date']);
$to = new \DateTime('today');
$search->field('published')->range($from, $to);
}
$search->expr()->operator('$text', array(
'$search' => $_POST['searchvideo'],
));
$search->limit(50);
$query = $search->getQuery();
$search = $query->execute();
Query returned and executed by Doctrine Mongodb in Symfony profiler is :
db.Video.find().limit(50);
Any help?

About upsert in pymongo

Each record in the collection has two key "ip" and "timestamp"
db.posts.update({'ip' : '127.0.0.1', 'timestamp' : {'$gt' : sometimestamp}}, {'$set' : {'timestamp' : time.time()}, True)
The command above will insert a new record, if field "ip" with "127.0.0.1" not in the collection or "timestamp" is less than sometimestamp
Now, if I want to insert a new record only "ip" with "127.0.0.1" not in collection, in other word, keep value of "ip" unique.
How to do ?
What you are probably trying to do is this:
if( ip=127)
if( ts > myts)
update;
else
DO NOTHING;
else
insert;
So essentially, you are having two different types of updates..One is going to acutally make a change in timestamp and other tells mongo to do nothing, i.e., not even make an insert.
I am guessing this is not possible with an upsert. So better use simple updates as follows:
db.posts.update ( { 'ip' : '127.0.0.1', 'timestamp' : { '$gt' : sometimestamp } } , { '$set' : { 'timestamp' : time.time() } , False)
And I don't know how you'd write it in Pymongo, but logically speaking, you do this:
if (db.posts.find_one( { 'ip':'127.0.0.1'} ) != null):
db.posts.update ( {'ip' : '127.0.0.1'}, { '$set' : {'timestamp' : time.time() } } )
Unfortunately, I can't comment on the performance..

MongoDB & PHP - Returning a count of a nested array

Imagine I have a MonogDB collection containing documents as follows:
{name: 'Some Name', components: {ARRAY OF ITEMS}}
How can I return the name and the count of items in components?
Do I have to use a map/reduce?
I am using PHP's Mongo extension.
EDIT: Snippet of current code in PHP (working) but I just want count of the components
$fields = array(
'name', 'components'
);
$cursor = $this->collection->find(array(), $fields);
$cursor->sort(array('created_ts' => -1));
if (empty($cursor) == true) {
return array();
} else {
return iterator_to_array($cursor);
}
Thanks,
Jim
You could use map-reduce or you could use a simple group query as follows. Since I am assuming that your name property is a unique key, this should work even though it isn't a reason that you'd normally use the group function:
db.test.group({
key: { name:true },
reduce: function(obj,prev) {
var count = 0;
for(k in obj.components)
count++;
prev.count = count;
},
initial: { count: 0}
});
You mentioned that you have an array of components, but it appears that you are storing components as an object {} and not and array []. That is why I had to add the loop in the reduce function, to count all of the properties of the components object. If it were actually an array then you could simply use the .length property.
In PHP it would look something like this (from the Manual):
$keys = array('name' => 1);
$initial = array('count' => 0);
$reduce =<<<JS
function(obj,prev) {
var count = 0;
for(k in obj.components)
count++;
prev.count = count;
},
JS;
$m = new Mongo();
$db = $m->selectDB('Database');
$coll = $db->selectCollection('Collection');
$data = $coll->group($keys, $initial, $reduce);
Finally, I would strongly suggest that if you are trying to access the count of your components on a regular basis that you store the count as an additional property of the document and update it whenever it changes. If you are attempting to write queries that filter based on this count then you will also be able to add an index on that components property.
You could use db.eval() and write the calculation in JavaScript.
Jim-
These are two separate operations; Unless you want to leverage PHP's count on the results you get which you would then do something like:
$m = new Mongo();
$db = $m->selectDB('yourDB');
$collection = $db->selectCollection('MyCollection');
$cursor = $collection->find(array(), array("name"=>1, "components"=>1));
foreach($cursor as $key){
echo($key['name'].' components: '.count($key['components']);
}
Ran across this today, If your using the new driver with aggregate you can do this in php, ( given this schema )
{name: 'Some Name', components: {ARRAY OF ITEMS}}
In PHP:
$collection = (new Client())->db->my_collection;
$collection->aggregate([
'$match' => ['name' => 'Some Name'],
'$group' => [
'_id' => null,
'total'=> ['$sum' => "\$components"]
]
]);
The trick here with PHP is to escape the $ dollar sign, this is basically what the mongo documentation says when using size or sum
https://docs.mongodb.com/manual/reference/operator/aggregation/size/
https://docs.mongodb.com/manual/reference/operator/aggregation/sum/
The problem I had is mongo puts fields in as "$field" and PHP doesn't like that at all because of the way it does variable interpolation. However, once you escape the $, it works fine.
I think for this particular case you'd need to do something similar but with $project instead of $group Like this
$collection = (new Client())->db->my_collection;
$collection->aggregate([
'$match' => ['name' => 'Some Name'],
'$project' => [
'name' => "\$name",
'total'=> ['$sum' => "\$components"]
]
]);
This is an old question but seeing as there is no answer picked, I'll just leave this here.