I'm trying to query my db that have this document format:
{ "_id" : ObjectId("520b8b3f8bd94741bf006033"), "value" : 0.664, "timestamp" : ISODate("2013-08-14T13:48:35Z"), "cr" : ISODate("2013-08-14T13:50:55.834Z") }
I can get the last records from a datetime with this query:
db.mycol.find({timestamp:{$gt: ISODate("2013-08-14T13:48:00Z")}}).sort({x:1});
But I'm trying to get a set with the value fields and timestamps from 18 minutes ago.
To find last object in collection, at first sort() to sort the values. Use limit() to get number of values i.e. if you want only the last object, then use limit(1).
You can also use min function like this. $min is an accumulator operator available only in the $group stage. UPDATE: Changed in version 3.2: $min is available in the $group and $project stages. In previous versions of MongoDB, $min is available in the $group stage only.
One can identify slow queries in MongoDB by enabling the profiler and configuring it to its some specifications or executing db. currentOp() on a running mongod instance. By looking at the time parameters on the returned result, we can identify which queries are lagging.
You can specify a particular date by passing an ISO-8601 date string with a year within the inclusive range 0 through 9999 to the new Date() constructor or the ISODate() function. These functions accept the following formats: new Date("<YYYY-mm-dd>") returns the ISODate with the specified date.
For the 18 minutes part, that's not really about MongoDB, but about JavaScript and what's available in the mongo shell:
query = { timestamp: { // 18 minutes ago (from now) $gt: new Date(ISODate().getTime() - 1000 * 60 * 18) } }
Works in the mongo shell, but using Mongo drivers for other languages would be really different.
To "project" over a smaller schema with both values and timestamps:
projection = { _id: 0, value: 1, timestamp: 1, }
Applying both:
db.mycol.find(query, projection).sort({timestamp: 1});
Well, that's still not a "set" since there might be duplicates. To get rid of them you can use the $group
from the aggregation framework:
db.mycol.aggregate([ {$match: query}, {$group: { _id: { value: "$value", timestamp: "$timestamp", } }}, {$project: { value: "$_id.value", timestamp: "$_id.timestamp", }}, {$sort: {timestamp: 1}}, ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With