I've been trying to find a way to create an ISODate object whith pyMongo client, but without any success so far.
I use http://pypi.python.org/pypi/pymongo3 client, which is the only serious one available in Python 3 for now, but the problem doesn't seem to come from this specific pymongo version.
I'd like to know if any of you has found a solution to use this MongoDB object type from a pymongo client... thanks for your help !
You just need to store an instance of datetime.datetime.
Inserting from the python shell:
>>> c.test.test.insert({'date': datetime.datetime.utcnow()})
ObjectId('4e8b388367d5bd2de0000000')
>>> c.test.test.find_one()
{u'date': datetime.datetime(2011, 10, 4, 16, 46, 59, 786000), u'_id': ObjectId('4e8b388367d5bd2de0000000')}
Querying in the mongo shell:
> db.test.findOne()
{
"_id" : ObjectId("4e8b388367d5bd2de0000000"),
"date" : ISODate("2011-10-04T16:46:59.786Z")
}
For those who are wondering how to create ISODate from timestamp:
ts = time.time()
isodate = datetime.datetime.fromtimestamp(ts, None)
This will create datetime object with no timezone. When inserted to MongoDB it will get converted to proper ISODate().
Also, I strongly recommend looking at Python TimeTransitionsImage. Note that tuple here is named tuple (equivalent to struct in C). And also note that tuple fields are not the same as in C counterparts, even though the naming is the same (for instance, tm_wday starts with Monday and not Sunday).
Actually that does not work either. When you try to use either utcfromtimestamp or fromtimestamp, the program errors out saying that it needs a float. Just parse the string into a date time object and use that directly in the Mongodb. filter
from_dt = datetime.strptime('2018-04-01','%Y-%m-%d')
#from_dts = datetime.utcfromtimestamp(from_dt)
to_dt = datetime.strptime('2018-04-30','%Y-%m-%d')
#to_dts = datetime.utcfromtimestamp(to_dt)
filterCondition = {
"LastLogin" : { "$lte" : to_dt},
"LastLogin" : { "$gte" : from_dt}
}
And then
db[(colName)].find({ "<colName>" : filterCondition })
Would work...
result = db.objects.insert_one(
{"last_modified": datetime.datetime.utcnow()})
Here utc stands for Universal Time Coordinates.
For create a document with specific date, for example 03/10/1999, run this:
from datetime import datetime
from pymongo import MongoClient
db = MongoClient().db_name
date = datetime(1999, 03, 10)
db.collection.insert_one({'date': date})
Related
I have around 30-40 records like the example before in my database and I'm looking to get the notifications that are less than 1 month old (from today's date). Is there a way in Mongo to get these results without having to pass in a today's date via JavaScript? Or if I do have to pass it in via JavaScript, how would I process this against my created date?
{
"_id" : ObjectId("48445b4dc72153e9ad7f3bfb"),
"notificationID" : "78723asd5-vnbb-xv31-afe0-fa9asf164e4",
"notification" : "Notification #1",
"created" : ISODate("2016-11-21T20:33:53.695Z")
}
Any help is appreciated, thanks.
MongoDB has its own Javascript interpreter so, unless your MongoDB server has a different date than your system, it knows the current date so you easily use simple Javascript to compute the value you're looking for using a regular Date object and use it in your query.
var d = new Date();
d.setMonth(d.getMonth() - 1); //1 month ago
db.data.find({created:{$gte:d}}); //change "data" for your collection's name
If you need a different date than your database's, I'm afraid you'll have to somehow pass it as a parameter.
const now = new Date()
const temp = new Date(now).setMonth(now.getMonth() - 6);
const priorSix = new Date(temp)
Table.find({"date" : {$gte: priorSix, $lt: new Date()}}, (err, tables) => {
if(err) throw new Error(err)
res.status(200).json(tables)
}).populate('foodList.item')
This code worked for me. It retrieves documents of the last 6 month :)
I am inserting json file into Mongodb(with Scala/Play framework) and the same getting/downloading it into my view page for some other requirement, but this time it is coming with one "_id" parameter in the json file.
But I need only my actual json file only that is not having any any "_id" parameter. I have read the Mongodb tutorial, that by default storing it with one _id for any collection document.
Please let me know that how can I get or is there any chance to get my actual json file without any _id in MongoDB.
this is the json result which is storing in database(I don't need that "_id" parameter)
{
"testjson": [{
"key01": "value1",
"key02": "value02",
"key03": "value03"
}],
"_id": 1
}
If you have a look at ReactiveMongo dev guide and to its API, you can see it support projection in a similar way as the MongoDB shell.
Then you can understand that you can do
collection.find(selector = BSONDocument(), projection = BSONDocument("_id" -> 0))
Or, as you are using JSON serialization:
collection.find(selector = Json.obj(), projection = Json.obj("_id" -> 0))
You can use this query in the shell:
db.testtable.find({},{"_id" : false})
Here we are telling mongoDB not to return _id from the collection.
You can also use 0 instead of false, like this:
db.testtable.find({},{"_id" : 0})
for scala you need to convert it in as per the driver syntax.
MongoDB shell version: 2.0.4
Want to insert date as 'date datatype' from mongo command line.
db.my_date_collection.insert(
{"user_id" : 91,
"event_timestamp" :new Date("09-AUG-12 05.30.28.402000 AM")
});
Above query add record but change date from "09-AUG-12 05.30.28.402000 AM" to "1970-01-01T00:00:00Z"
> db.my_date_collection.findOne()
{
"_id" : ObjectId("54168ddc289a635d725d86fb"),
"user_id" : 91,
"event_timestamp" : ISODate("1970-01-01T00:00:00Z")
}
Plus it also didn't save 'date data' as date 'datatype'
typeof db.my_date_collection.findOne().event_timestamp;
object
Can someone help me insert data as date type from mongo prompt?
Additionally can some one tell me how to insert the 'date as date datatype type' from a tsv file? as i got the same issue in loading tsv from mongoimport.
Thanks
The date is not in a valid format to be parsed by the date constructor. Try the equivalent value in a valid format (I'm assuming UTC time since you didn't include a timezone):
"09-AUG-12 05.30.28.402000 AM" => "2012-08-09T05:30:28.402"
> var my_date = ISODate("2012-08-09T05:30:28.402")
> db.my_dates.insert({ "x" : my_date })
> var doc = db.my_dates.findOne()
> doc.x instanceof Date
true
The return value is of Date type, but Javascript isn't object oriented so the meaning of that and how to determine if something is of Date type are different than you are expecting, apparently. Use instanceof to check is something is of a certain type or "inherits" from that type.
Your code is good. Take a look at typeof doc. It can return more generic type. Use instanceof to check a type:
db.my_date_collection.findOne().event_timestamp instanceof Date
I have the following kind of document:
{
"_id" : ObjectId("538d64a11ca6e50941fda4d9"), "_id" : "538d518e20b8fd642e0000e8",
"posts" : "some stuff", "date" : "2014-06-02"
}
Using comparison operators for a string date (Not the Mongodb ISODate) works:
> collection.find({"date": {"$gte": "2014-06-02"}})
So why shall we (bother to) convert string dates to an ISODate then?
Probably the biggest advantage of using the MongoDB BSON Date type instead of a string is that you can only use the aggregate Date operators with BSON Date values.
But if you don't need to do any aggregation of your data, using a sortable string format to represent dates is fine and often cleaner as you don't need to deal with time zone related display problems.
I'm looking to do an extract from a MongoDB from a particular date.
Since I'm using a component in Talend that sends the query I'm kind of limited in the sense that I can't use multiple lines of code.
Can you do a date limitation directly in the find-method?
db.example.find({ ts: { $gt: lowdate} });
Where lowdate is substituted for something that I hope any of you can figure out.
Many thanks!
PS. The date format in the mongodb, if that matters, is "Dec 16, 2011 7:37:06 PM".
--- Update ---
From my MongoDB:
, "ty" : "auth", "ts" : "Dec 16, 2011 3:28:01 PM",
which suggests the format of the timestamp (ts) is a string. Correct?
If the date is stored as a string in that format, you will not be able to make a query. In order to fix this, I suggest you write a script in your favourite language that scans all the documents and convert this date-as-a-string into a timestamp. You can either overwrite the "ts" field, or create a new one, f.e. something called "ts_int".
For example, in PHP you would do:
<?php
$m = new Mongo();
$c = $m->mydbname->example;
foreach ( $c->find() as $item )
{
$item['ts_int'] = strtotime( $item['ts'] );
$c->update( $item );
}
?>