Mongoose find time furthest from other times in db - node.js

I have a program that runs every 5 minutes and checks the last time a users data was updated. If it's been greater than 4 hours an update routine is called but as the service grows, I've seen some spikes in the number of calls at given times. I want to start spreading out the update times. Since I know each time the program updated each users data last, I was wondering if there was an elegant way to find the largest gap between times and set the new users update time to that?
Here's an example. Given the following data:
{
"_id": "1",
"updatedAt": "2018-01-17T01:12:33.807Z"
},{
"_id": "2",
"updatedAt": "2018-01-17T03:17:33.807Z"
},{
"_id": "3",
"updatedAt": "2018-01-17T02:22:33.807Z"
},{
"_id": "4",
"updatedAt": "2018-01-17T02:37:33.807Z"
}
The largest time between the given updates is 1 hour and 10 minutes between id: 1 and id: 3. I want a function that can find that largest gap of time and returns the a suggested update time for the next item added to the database of '2018-01-17T01:47:33.807Z'. Which was calculated by taking the 1 hour and 10 minutes and dividing it by 2 and then adding it to id: 1's date.
I would also like to spread out all the existing users update time but I suppose that would be a different function.

You can't use aggregation framework for a difference style comparison. However you can use map reduce to get the largest time diff between documents.
Something like
db.col.mapReduce(
function () {
if (typeof this.updatedAt != "undefined") {
var date = new Date(this.updatedAt);
emit(null, date);
}
},
function(key, dates) {
result = {"prev":dates[0].getTime(), "last":dates[0].getTime(), "diff":0}
for (var ix = 1; ix < dates.length; ix++) {
value = dates[ix].getTime();
curdiff = value - result.prev;
olddiff = result.diff;
if(olddiff < curdiff)
result = {"prev":value, "diff":curdiff, "last":result.prev};
}
return result;
},
{
"sort":{"updatedAt":1},
"out": { "inline": 1 },
"finalize":function(key, result) {
return new Date(result.last + result.diff/2);
}
}
)
Aggregation query:
db.col.aggregate([
{"$match":{"updatedAt":{"$exists":true}}},
{"$sort":{"updatedAt":1}},
{"$group":{
"_id":null,
"dates":{"$push":"$updatedAt"}
}},
{"$project":{
"_id":0,
"next":{
"$let":{
"vars":{
"result":{
"$reduce":{
"input":{"$slice":["$dates",1,{"$subtract":[{"$size":"$dates"},1]}]},
"initialValue":{"prev":{"$arrayElemAt":["$dates",0]},"last":{"$arrayElemAt":["$dates",0]},"diff":0},
"in":{
"$cond":[
{"$lt":["$$value.diff",{"$subtract":["$$this","$$value.prev"]}]},
{"prev":"$$this","last":"$$value.prev","diff":{"$subtract":["$$this","$$value.prev"]}},
"$$value"
]
}
}
}
},
"in":{
"$add":["$$result.last",{"$divide":["$$result.diff",2]}]
}
}
}
}}
])

Related

How to calculate the amount with conditional?

I have such documents in MongoDB:
{
"_id":{
"$oid":"614e0f8fb2f4d8ea534b2ccb"
},
"userEmail":"abc#example.com",
"customId":"abc1",
"amountIn":10,
"amountOut":0,
"createdTimestamp":1632505743,
"message":"",
"status":"ERROR",
}
The amountOut field can be 0, or a positive numeric value.
I need to calculate the sum of the amountIn and amountOut fields only if it is positive.
At the moment I am doing it like this:
query = {
'createdTimestamp': {'$gte': 1632430800},
'createdTimestamp': {'$lte': 1632517200}
}
records = db.RecordModel.objects(__raw__=query).all()
total_amount = 0
for record in records:
if record.amountOut > 0:
total_amount += record.amountOut
else:
total_amount += record.amountIn
But this is very slow.
I know mongoengine has a sum method:
total_amount = db.PaymentModel.objects(__raw__=query).sum('amountIn')
But I don't know how to use the condition for this method.
Maybe there are some other ways to calculate the amount with the condition I need faster?
You can use mongoengine's aggregation api which just allows you to execute aggregations normally.
Now you can use this pipeline in code which utilizes $cond:
query = {
'createdTimestamp': {'$gte': 1632430800, '$lte': 1632517200},
}
pipeline = [
{"$match": query},
{
"$group": {
"_id": None,
"total_amount": {
"$sum": {
"$cond": [
{
"$gt": [
"$amountOut",
0
]
},
"$amountOut",
"$amountIn"
]
}
}
}
}
]
records = db.RecordModel.objects().aggregate(pipeline)
Mongo Playground

Find object from a collection according to created date

I have a collection ticket_masters,which contain createdAt field and it store the date and time .
[
{
"_id": "5e78f2ddc0e09128e81db47a",
"NAME": "Jasin",
"PHONE": "2252545414",
"MAIL": "sdsdm#m.com",
"createdAt": "2020-03-23T17:33:17.470Z",
"updatedAt": "2020-03-23T17:33:17.470Z",
"__v": 0
}
]
Now i want find records according to createAt field from the user collection. Already tried with the following code snippet.
db.getCollection('ticket_masters').find({
"createdAt" : '2020-03-17T18:30:00.237+00:00'
})
Output :
Fetched 0 record(s) in 1ms
But zero records found as per the above code snippet.Kindly help me to resolve issues
Thank you
By specifying the Date type.
The $eq operator matches documents where the value of a field equals the specified value.
// Date and time
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt": {$eq: new Date('2020-03-17T18:30:00.237+00:00')}
}
},
])
OR
// Only Date
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt": {"$gte": new Date("2020-03-17"), $lt : new Date("2020-03-18") }
}
},
])
The dates you saved were new Date(), which includes the time components. To query those times you need to create a date range that includes all moments in a day
Using momentjs
Example:
// start today
var start = moment().startOf('day');
// end today
var end = moment(today).endOf('day');
{ createdAt: { '$gte': start, '$lte': end }
$gt Matches values that are greater than a specified value.
$lt Matches values that are less than a specified value.
For more information: https://docs.mongodb.com/manual/reference/operator/query-comparison/
Hope this will help you.
db.getCollection('ticket_masters').find({
"createdAt" : ISODate("2020-03-17T18:30:00.237+00:00")
})
or you can try this.
db.getCollection('ticket_masters').aggregate([
{
$match: {
"createdAt":ISODate("2020-03-17T18:30:00.237+00:00")
}
},
])

Compare with time part only in mongodb query [duplicate]

I have a MongoDB datastore set up with location data stored like this:
{
"_id" : ObjectId("51d3e161ce87bb000792dc8d"),
"datetime_recorded" : ISODate("2013-07-03T05:35:13Z"),
"loc" : {
"coordinates" : [
0.297716,
18.050614
],
"type" : "Point"
},
"vid" : "11111-22222-33333-44444"
}
I'd like to be able to perform a query similar to the date range example but instead on a time range. i.e. Retrieve all points recorded between 12AM and 4PM (can be done with 1200 and 1600 24 hour time as well).
e.g.
With points:
"datetime_recorded" : ISODate("2013-05-01T12:35:13Z"),
"datetime_recorded" : ISODate("2013-06-20T05:35:13Z"),
"datetime_recorded" : ISODate("2013-01-17T07:35:13Z"),
"datetime_recorded" : ISODate("2013-04-03T15:35:13Z"),
a query
db.points.find({'datetime_recorded': {
$gte: Date(1200 hours),
$lt: Date(1600 hours)}
});
would yield only the first and last point.
Is this possible? Or would I have to do it for every day?
Well, the best way to solve this is to store the minutes separately as well. But you can get around this with the aggregation framework, although that is not going to be very fast:
db.so.aggregate( [
{ $project: {
loc: 1,
vid: 1,
datetime_recorded: 1,
minutes: { $add: [
{ $multiply: [ { $hour: '$datetime_recorded' }, 60 ] },
{ $minute: '$datetime_recorded' }
] }
} },
{ $match: { 'minutes' : { $gte : 12 * 60, $lt : 16 * 60 } } }
] );
In the first step $project, we calculate the minutes from hour * 60 + min which we then match against in the second step: $match.
Adding an answer since I disagree with the other answers in that even though there are great things you can do with the aggregation framework, this really is not an optimal way to perform this type of query.
If your identified application usage pattern is that you rely on querying for "hours" or other times of the day without wanting to look at the "date" part, then you are far better off storing that as a numeric value in the document. Something like "milliseconds from start of day" would be granular enough for as many purposes as a BSON Date, but of course gives better performance without the need to compute for every document.
Set Up
This does require some set-up in that you need to add the new fields to your existing documents and make sure you add these on all new documents within your code. A simple conversion process might be:
MongoDB 4.2 and upwards
This can actually be done in a single request due to aggregation operations being allowed in "update" statements now.
db.collection.updateMany(
{},
[{ "$set": {
"timeOfDay": {
"$mod": [
{ "$toLong": "$datetime_recorded" },
1000 * 60 * 60 * 24
]
}
}}]
)
Older MongoDB
var batch = [];
db.collection.find({ "timeOfDay": { "$exists": false } }).forEach(doc => {
batch.push({
"updateOne": {
"filter": { "_id": doc._id },
"update": {
"$set": {
"timeOfDay": doc.datetime_recorded.valueOf() % (60 * 60 * 24 * 1000)
}
}
}
});
// write once only per reasonable batch size
if ( batch.length >= 1000 ) {
db.collection.bulkWrite(batch);
batch = [];
}
})
if ( batch.length > 0 ) {
db.collection.bulkWrite(batch);
batch = [];
}
If you can afford to write to a new collection, then looping and rewriting would not be required:
db.collection.aggregate([
{ "$addFields": {
"timeOfDay": {
"$mod": [
{ "$subtract": [ "$datetime_recorded", Date(0) ] },
1000 * 60 * 60 * 24
]
}
}},
{ "$out": "newcollection" }
])
Or with MongoDB 4.0 and upwards:
db.collection.aggregate([
{ "$addFields": {
"timeOfDay": {
"$mod": [
{ "$toLong": "$datetime_recorded" },
1000 * 60 * 60 * 24
]
}
}},
{ "$out": "newcollection" }
])
All using the same basic conversion of:
1000 milliseconds in a second
60 seconds in a minute
60 minutes in an hour
24 hours a day
The modulo from the numeric milliseconds since epoch which is actually the value internally stored as a BSON date is the simple thing to extract as the current milliseconds in the day.
Query
Querying is then really simple, and as per the question example:
db.collection.find({
"timeOfDay": {
"$gte": 12 * 60 * 60 * 1000, "$lt": 16 * 60 * 60 * 1000
}
})
Of course using the same time scale conversion from hours into milliseconds to match the stored format. But just like before you can make this whatever scale you actually need.
Most importantly, as real document properties which don't rely on computation at run-time, you can place an index on this:
db.collection.createIndex({ "timeOfDay": 1 })
So not only is this negating run-time overhead for calculating, but also with an index you can avoid collection scans as outlined on the linked page on indexing for MongoDB.
For optimal performance you never want to calculate such things as in any real world scale it simply takes an order of magnitude longer to process all documents in the collection just to work out which ones you want than to simply reference an index and only fetch those documents.
The aggregation framework may just be able to help you rewrite the documents here, but it really should not be used as a production system method of returning such data. Store the times separately.

How to get the count of element in a node saved in dynamo db using doClient.scan()

In doClient.scan() is there any way to set the count of elements stored in a particular node?
As per the below example i need to add a new node "questionCount" to the below result which should contain the total number of reference_id in node questionList. is there any way other than iterating the result and adding a new node?
Expected Output
{
"status": 1,
"data": [
{
"questionList": [
{
"reference_id": "0df55215-90de-407a-b077-7017924556d3"
},
{
"reference_id": "0df55215-90de-407a-b077-7017924556d3"
},
{
"reference_id": "0df55215-90de-407a-b077-701997924556d3"
}
],
"testName": "sample test231s",
"testId": "2e97e40c-82cb-4126-9f47-b6a93687a59c",
"questionCount": 3
}
]
}
As you add questions to questionList with list_append, you could also increment the questionCount attribute with an UpdateExpression SET data.questionList = list_append(data.questionList, :newQuestion), ADD questionCount :one and ExpressionAttributeValues {":newQuestion": {"reference_id": "blah"}, ":one": 1}.

Elasticsearch: aggregation with interval hour

I have ~100 documents coming in per hour. Every document has a viewers property (integer).
By the end of the day I want to aggregate an array of 24 documents, one for every hour of the day, represented by the document with the highest viewers count.
My query so far:
// query, fetch all documents of a specific day
var query = {
bool : {
filter : [
{
range : {
'created' : {
gte : day,
lte : day + (60 * 60 * 24)
}
}
}
]
}
}
// aggregation
var aggs = {
// ?
}
I think this could be achieved using Date Histogram plus Top Hits aggregations. Look at this:
{
"size": 0,
"aggs": {
"articles_over_time": {
"date_histogram": {
"field": "created",
"interval": "minute"
},
"aggs": {
"Viewers": {
"top_hits": {
"size": 1,
"sort": [
{
"viewers": {
"order": "desc"
}
}
]
}
}
}
}
}
}
Date Histogram aggregation will create buckets for each hour in filtered date range and top hits agg will bring back document with highest viewers (we're ordering documents by viewers in descending order and bringing top 1 hit).
Let me know if this works.

Resources