How to count value of matching with the field value in mongoDB - node.js

I have a document in which perform 2 task.
I am new in mongoDB ,These tasks are very small and trying to explain.
To calculate number of users which have values of start hour, start Min, and start Sec these values should be less than or equal to start_min, start_hour which is defined in dObject.(We have to calculate number of users which come in an organisation ("orgId") earlier or at on time, Users have startHour,startMin and startSec this values should be equal or less than values which are defined in dObject Data (start_hour 10 and start_min 0) ).
To calculate number of users which have values of start hour, start Min, and start Sec these values should be greater to start_min, start_hour which is defined in dObject.(We have to calculate number of users which come in an organisation ("orgId") late Users have startHour,startMin and startSec this values should be greater than values which are defined in dObject Data (start_hour 10 and start_min 0) ).
NOTE
consider end_sec and start_sec with zero(0) in dObject Data. and keeping in mind organization Id and shiftId should be unique(By grouping).
MongoDB Document is give below.
{
"_id" : {
"orgId" : "af39bc69-1938-4149-b9f7-f101fd9baf73",
"userId" : "68c88420-4c22-11e7-ad9f-e5d77ee44b6c",
"checkinShiftId" : "7803421a-a680-4173-99af-a55c6f211724"
},
"lastSeen" : ISODate("2018-01-19T16:44:47.467+05:30"),
"firstSeen" : ISODate("2018-01-19T10:27:44.217+05:30"),
"dObjectInformation" : [ ],
"startHour" : 10,
"startMin" : 27,
"startSec" : 44,
"lastHour" : 16,
"lastMin" : 44,
"lastSec" : 47
},
{
"_id" : {
"orgId" : "af39bc69-1938-4149-b9f7-f101fd9baf73",
"userId" : "5cce5410-dca1-11e6-a87c-29432312f160",
"checkinShiftId" : "7803421a-a680-4173-99af-a55c6f211724"
},
"lastSeen" : ISODate("2018-01-19T20:32:50.041+05:30"),
"firstSeen" : ISODate("2018-01-19T11:05:10.095+05:30"),
"dObjectInformation" : [
{
"_id" : "5de84f30-6c62-11e7-9a37-dfd3a80c2c8c",
"dObjectData" : {
"end_min" : "0",
"end_hour" : "19",
"start_min" : "0",
"start_hour" : "10",
"dObjectId" : "7803421a-a680-4173-99af-a55c6f211724",
"objectName" : "shift",
"objectId" : "5a6ecc6a-1d71-4400-adc6-2eb3b39cb5d0",
"updatedOn" : ISODate("2018-01-16T17:48:22.990+05:30"),
"addedOn" : ISODate("2017-07-19T14:42:19.620+05:30")
}
}
],
"startHour" : 11,
"startMin" : 5,
"startSec" : 10,
"lastHour" : 20,
"lastMin" : 32,
"lastSec" : 50
}
Expected Result
{
"shiftId":"avc",
"orgId":"2323"
"numberOfUserReachBeforeOrEqualOnTime":"12",
"numberOfUserReachAfterOnTime":"4"
}
Please suggest me how to use aggregate Query.Thanks!

Related

How is bounce rate calculated in Google Analytics?

Pulling some of the metrics from Google Analytics (including bounce rate). Saved data given below.
Which metrics are used to calculate bounce rate?
How can I calculate bounce rate using other metrics values?
{
"_id" : ObjectId("5ecd09c83f80224b219b6827"),
"source" : "(direct)",
"medium" : "(none)",
"pagePath" : "/",
"channelGrouping" : "Direct",
"deviceCategory" : "desktop",
"date" : "20180326",
"users" : 6,
"sessions" : 6,
"bounces" : 3,
"avgSessionDuration" : 95.3333333333333,
"pageviews" : 6,
"newUsers" : 5,
"sessionDuration" : 572,
"pageviewsPerSession" : 1,
"bounceRate" : 50,
"goal" : 0,
"accId" : "92025510",
"agencyId" : ObjectId("5e3136e4c2a1b60c89ae07cc"),
"accountMongoId" : ObjectId("5e4ee454cdc4db6a02696405"),
"dataForDate" : "2018-04-01",
"dataForDateTime" : ISODate("2018-03-26T00:00:00.000Z")
}
/* 2 */
{
"_id" : ObjectId("5ecd09c83f80224b219b682c"),
"source" : "(direct)",
"medium" : "(none)",
"pagePath" : "/",
"channelGrouping" : "Direct",
"deviceCategory" : "desktop",
"date" : "20180401",
"users" : 1,
"sessions" : 1,
"bounces" : 1,
"avgSessionDuration" : 0,
"pageviews" : 1,
"newUsers" : 1,
"sessionDuration" : 0,
"pageviewsPerSession" : 1,
"bounceRate" : 100,
"goal" : 0,
"accId" : "92025510",
"agencyId" : ObjectId("5e3136e4c2a1b60c89ae07cc"),
"accountMongoId" : ObjectId("5e4ee454cdc4db6a02696405"),
"dataForDate" : "2018-04-01",
"dataForDateTime" : ISODate("2018-04-01T00:00:00.000Z")
}
bounce rate
The percentage of single-page session (i.e., session in which the person left the property from the first page).
This is an internal calculation done by google its not one that you can calculate yourself i suggest using ga:bouncerate

Query an array in MongoDB

I have this collection in MongoDB:
{
"_id" : ObjectId("5df013b10a88910018267a89"),
"StockNo" : "33598",
"Description" : "some description",
"detections" : [
{
"lastDetectedOn" : ISODate("2020-01-29T04:36:41.191+0000"),
"lastDetectedBy" : "comp-t",
"_id" : ObjectId("5e3135f68c9e930017de8aec")
},
{
"lastDetectedOn" : ISODate("2019-12-21T18:12:06.571+0000"),
"lastDetectedBy" : "comp-n",
"_id" : ObjectId("5e3135f68c9e930017de8ae9")
},
{
"lastDetectedOn" : ISODate("2020-01-29T07:36:06.910+0000"),
"lastDetectedBy" : "comp-a",
"_id" : ObjectId("5e3135f68c9e930017de8ae7")
}
],
"createdAt" : ISODate("2019-12-10T21:52:49.788+0000"),
"updatedAt" : ISODate("2020-01-29T07:36:22.950+0000"),
"__v" : NumberInt(0)
}
I want to search by StockNo and get the name of the computer that last detected it (lastDetectedBy) only if lastDetectedOn was in the last 5 minutes with Mongoose in node.js with Express.
I also have this collection:
{
"_id" : ObjectId("5df113b10d35670018267a89"),
"InvoiceNo" : "1",
"InvoiceDate" : ISODate("2020-01-14T02:18:11.196+0000"),
"InvoiceContact : "",
"isActive" : true
},
{
"_id" : ObjectId("5df013c90a88910018267a8a"),
"InvoiceNo" : "2",
"InvoiceDate" : ISODate("2020-01-14T02:18:44.279+0000"),
"InvoiceContact : "Bob Smith",
"isActive" : true
},
{
"_id" : ObjectId("5e3096bb8c9e930017dc6e20"),
"InvoiceNo" : "3",
"InvoiceDate" : ISODate("2020-01-14T02:19:50.155+0000"),
"InvoiceContact : "",
"isActive" : true
}
And I want to update all the documents with empty InvoiceContact which has been issued in the last 30 seconds (or any date range between now and sometime in the past) with isActive equals true to isActive equals false. So for example, the first record has been issued in the last 30 seconds without InvoiceContact and isActive is true so this must be updated but the next two records will remain untouched for different reasons, the second record has InvoiceContact and the third record is out of range.
First Part
var mins5 = new Date(ISODate() - 1000* 60 * 5 )
db.getCollection('user').find({$and:[
{ "StockNo":"33598"},
{"detections.lastDetectedOn" : { $gte : mins5 }}
]})
.map(function(list){
var results = [];
list.detections.forEach(function (detections){
if(detections.lastDetectedOn > mins5){
results.push(detections.lastDetectedBy);
}
})
return results;
});
Second Part could be solved by a similar query using update instead of find.

Calculate active time of an employee

I am trying to create a timesheet for employees where I am saving each event(Active, Inactive) as a timestamp in MongoDB. How to calculate the active time of an employee from a given time?
{
"_id" : ObjectId("5d8c8dcca4c6010e29140e0e"),
"activityAt" : ISODate("2019-09-26T10:07:05.388+0000"),
"version" : NumberInt(1),
"deleted_at" : null,
"event" : "ACTIVE",
"employeeId" : ObjectId("5d78fba602c9265fc7ad6273"),
"created_at" : ISODate("2019-09-26T10:07:08.479+0000"),
"modified_at" : ISODate("2019-09-26T10:07:08.479+0000")
}
// ----------------------------------------------
{
"_id" : ObjectId("5d8c8dcca4c6010e29140e0f"),
"activityAt" : ISODate("2019-09-26T11:07:05.388+0000"),
"version" : NumberInt(1),
"deleted_at" : null,
"event" : "INACTIVE",
"employeeId" : ObjectId("5d78fba602c9265fc7ad6273"),
"created_at" : ISODate("2019-09-26T11:07:08.481+0000"),
"modified_at" : ISODate("2019-09-26T11:07:08.481+0000")
}
For every entry that is 'active', take the date from ISODate and subtract from it the current date (or any given time). The result will be all the active time the employee has.
In pseudocode:
active_time = 0
for entry in db:
if entry.event == 'ACTIVE':
active_time = active_time + (current_date - entry.ISODate)
return active_time
The only thing you would need to do is convert the date into something that can be subtracted/added/etc. A solution would be to convert it to hours.
Good luck!

Sort JSON document by values embedded in an array of objects

I have a document in the below format. The goal is to group the document by student name and sort it by rank in the ascending order. Once that is done, iterate through the rank(within a student) and if each subsequent rank is greater than the previous one, the version field needs to be incremented. As part of a pipeline, student_name will be passed to me so matching by student name should be good instead of grouping.
NOTE: Tried it with python and works to some extent. A python solution would also be great!
{
"_id" : ObjectId("5d389c7907bf860f5cd11220"),
"class" : "I",
"students" : [
{
"student_name" : "AAA",
"Version" : 2,
"scores" : [
{
"value" : "50",
"rank" : 2
},
{
"value" : "70",
"rank" : 1
}
]
},
{
"student_name" : "BBB",
"Version" : 5,
"scores" : [
{
"value" : 80,
"rank" : 2
},
{
"value" : 100,
"rank" : 1
},
{
"value" : 100,
"rank" : 1
}
]
}
]
}
I tried this piece of code to sort
def version(student_name):
db.column.aggregate(
[
{"$unwind": "$students"},
{"$unwind": "$students.scores"},
{"$sort" : {"students.scores.rank" : 1}},
{"$group" : {"students.student_name}
]
)
for i in range(0,(len(students.scores)-1)):
if students.scores[i].rank < students.scores[i+1].rank:
tag.update_many(
{"$inc" : {"students.Version":1}}
)
The expected output for student AAA should be
{
"_id" : ObjectId("5d389c7907bf860f5cd11220"),
"class" : "I",
"students" : [
{
"student_name" : "AAA",
"Version" : 3, #version incremented
"scores" : [
{
"value" : "70",
"rank" : 1
},
{
"value" : "50",
"rank" : 2
}
]
}
I was able to sort the document.
pipeline = [
{"$unwind": "$properties"},
{"$unwind": "$properties.values"},
{"$sort" : {"$properties.values.rank" : -1}},
{"$group": {"_id" : "$properties.property_name", "values" : {"$push" : "$properties.values"}}}
]
import pprint
pprint.pprint(list(db.column.aggregate(pipeline)))

how to find recent record of record matching particular criteria

{
"_id" : ObjectId("5514ecc73910d3e808b9417c"),
"endingReciptBookNumber" : 2999,
"startingReciptBookNumber" : 2900,
"User" : 8,
"allRecipt" : [
{
"recipt_Number" : 2999,
"amount" : 24124,
"_id" : ObjectId("5514ecc73910d3e808b94180")
},
{
"recipt_Number" : 100,
"amount" : 2414,
"_id" : ObjectId("5514ecc73910d3e808b9417f")
},
{
"recipt_Number" : 101,
"amount" : 242,
"_id" : ObjectId("5514ecc73910d3e808b9417e")
},
{
"recipt_Number" : 102,
"amount" : 2424,
"_id" : ObjectId("5514ecc73910d3e808b9417d")
}
],
"__v" : 0
}
I have many documents like this in a collection in mongoose .I want to find a latest entered recipt_Number for a particular user. like in this case it should give me 102 as answer.
i have also attached snippet of lines of code. Its also a way to get same result.
db.topics.find( {'User': 8}, { 'allRecipt': { $slice: -1 },'startingReciptBookNumber':0,'endingReciptBookNumber':0,'User':0,'_id':0,'__v':0 } )
query result like below
{
"allRecipt" : [
{
"recipt_Number" : 102,
"amount" : 2424,
"_id" : ObjectId("5514ecc73910d3e808b9417d")
}
]
}
Though query won't give any single number in result but it will give desired outcome through result.allRecipt.0.recipt_Number, Your desired number will always get into in 0 index. I think this is your desired number.
Here $slice make a difference.
Thanks

Resources