Find All Objects Created Before Specified Date - mongodb

Mongo has a nice feature that tells you when a document was created.
ObjectId("53027f0adb97425bbd0cce39").getTimestamp() = ISODate("2014-02-17T21:28:42Z")
How would I get about finding all documents that were created before lets say February 10th 2014? Searched around but doesn't seem like this question comes up. Any help is appreciated! Thanks!

You mean something like this?
db.YOUR_COLLECTION.find({YOUR_DATE_FIELD: { "$lt": ISODate("2014-02-10") }})
Guess that you have to make the same as JoJo recommended:
Convert a date to an ObjectId
Filter ID using $lt and returned ObjectId
Using pymongo you can do something like this:
gen_time = datetime.datetime(2014, 2, 10)
dummy_id = ObjectId.from_datetime(gen_time)
result = collection.find({"_id": {"$lt": dummy_id}})
Reference: http://api.mongodb.org/python/1.7/api/pymongo/objectid.html

Related

How to apply $lt to array elements?

I'm trying this (all documents have tags array):
db.find($lt: ['$tags.0.created', '2019-05-05'])
I want to fetch all documents where the first tag was created before the specified date. It doesn't work. I mean, it returns all elements. What's wrong in this query?
The actual find would look something like this:
db.YOURCOLLECTION.find({ 'tags.0.created': { $lt: '2019-05-05' } })
You can see it working here

Insert array during mongo insert [duplicate]

there are some questions here regarding how to save a result from a query into a javascript varialbe, but I'm just not able to implement them. The point is that I have a much difficult query, so this question is, in my opinion, unique.
Here is the problem. I have a collection namend "drives" and a key named "driveDate". I need to save 1 variable with the smallest date, and other with the biggest date.
The query for the smallest date is:
> db.drives.find({},{"_id":0,"driveDate":1}).sort({"driveDate":1}).limit(1)
The result is:
{ "driveDate" : ISODate("2012-01-11T17:24:12.676Z") }
how dan I save this to a variable, can I do something like:
tmp = db.drives.find({},{"_id":0,"driveDate":1}).sort({"driveDate":1}).limit(1)
Thanks!!!
Assuming you're trying to do this in the shell:
tmp = db.drives.find({}, {_id:0, driveDate:1}).sort({driveDate:1}).limit(1).toArray()[0]
find returns a cursor that you need to iterate over to retrieve the actual documents. Calling toArray on the cursor converts it to an array of docs.
After some time figuring out, I got the solution. here it is, for future reference:
var cursor = db.drives.find({},{"_id":1}).sort({"driveDate":1}).limit(1)
Then I can get the document from the cursor like this
var myDate = cursor.next()
That's it. Thanks for your help

Retrieve last document in a MongoDB using Pymongo and Flask

I'm working on a Raspberry Pi project that collects weather measurements and stores them in a Mongo database like this:
{
"_id": {
"$oid": "577975c874fece5775117209"
},
"timestamp": {
"$date": "2016-07-03T20:30:00.995Z"
},
"temp_f": 68.9,
"temp_c": 20.5,
"humidity": 50,
"pressure": 29.5
}
The data is going into the Mongo db just fine. Next, I'm trying to build a Flask-based dashboard that enables me to look at the recorded data. On one of the pages of the dashboard, I want to show the current recorded values, so what I need to do is pull out the last measurement and pass it to a flask template for rendering to the browser.
I found a post here that said I could use:
data = db.measurements.find().limit(1).sort({"$natural": -1})
but natural doesn't seem to be a valid option for the call to find.
This works:
measurement = mongo.db.measurements.find_one()
It pulls back one random measurement that I can then pass to the flask template, but how do I use sort to get the most recent one?
I tried:
measurement = mongo.db.measurements.find_one().sort([("timestamp", -1)])
but that generates an attribute error: AttributeError: 'dict' object has no attribute 'sort'
I've also tried:
cursor = mongo.db.measurements.find().limit(1).sort({"timestamp": -1})
but that doesn't work either.
I'm missing something here, can someone give me a quick, complete fix for this?
It turns out Pymongo has a different format for sort. You can't pass in a JSON object, you have to use a dict. Once I fixed that, it all works:
cursor = mongo.db.measurements.find().sort([('timestamp', -1)]).limit(1)

How do you search an array of documents in mongo dart?

How do I search an array of documents in mongodb using the dart programming language?
Im using https://pub.dartlang.org/packages/mongo_dart for the driver
The example db collection looks like this
"name": [
{"full":"Tyler Thompson",
"first":"Tyler",
"last":"Thompson"
}
]
Using the following query will help achieve your goal for the one name
String search = "Tyler";
{"name.full": {'\$regex': '${search}'}
Hope that helps! Couldn't find an example, so I thought I'd give one!:)
You can try to look at https://github.com/vadimtsushko/mongo_dart/blob/master/example/queries.dart
It is plausible that for your sample something like this would work:
coll.find(where.eq('name.full','Tyler'))
or maybe
coll.find(where.match('name.full','^Tyl[eo]r'))

How to use $regex in projection

My mongodb document looks like this,
{'finance_pl':
{'S':
{
'** 200903': {'reported_eps': '19.48'},
'200806': {'reported_eps': '18.8'}
}
}
}
** 200903 ==> year 2009 month 03.
Simple way to fetch reported_eps is this
db.collection.find(
{},
{'finance_pl.S.200803.reported_eps':1}
)
but the problem is i only have the year 2008 or 2009 the month part need to generate dynamically.
I need something like this
db.collection.find(
{},
{'finance_pl.S.2008[0-9]{2}.reported_eps':1}
)
[0-9]{2} --> python regex, to match two digits.
All the example I found in the documentation and in other places have not used $regex in projection part.
I am using pymongo. How should I solve this.
You cannot currently use dynamic field names in projection like this using regex or another operator.
I am unsure if there will ever be the ability to, I am unable to find anything meaningful on the JIRA.
At the moment the best way is to restructure for your queries.