Datediff query in mongodb - mongodb

I am not a expert in Mongodb so stuck at one point.
I have DTEnd column in my collection where i store end date of an event . I want to fetch closing soon events with criteria sysdate-DTEnd <2 could anybody let me know how to fetch the same in mongodb . Sample schema is as below
{ CorporateId: null, CorporateName: 'Nuclues Software', Description: 'Basic AngularJS Training First Semeseter Guys', EndDateTime: Thu Sep 05 2013 00:00:00 GMT+0530 (India Standard Time), NominationCount: 0, StartDateTime: Thu Sep 05 2013 00:00:00 GMT+0530 (India Standard Time), Status: null, ViewCount: 22, _id: 52298b8c60df891c30e553ca, Address: { ZipCode: '1212', City: '1212', State: '1212', StreetAddress: '1212', NearestLandMark: '1212' }, Nominations: [], Technologies: [ { Name: 'AngularJS' }, { Name: 'Asp.net' } ] }
Solved using $lt and $gte
> db.Training.find({EndDateTime:{ $gte: ISODate("2013-09-10T00:00:00.000Z"), $lt
: ISODate("2013-09-12T00:00:00.000Z")}}).count()

Related

How do I use the mongoDB Comparison Query Operator to check for values between createdAt dates?

I would like to view all the created users Meteor.users.find().fetch() that were created in the database between the beginning of 1st September and the end of 30th September. How do I achieve this in code.
Find inline my failed attempt:
var beginningOfMonth = new Date();
beginningOfMonth.setMonth(8, 1);
console.log("beginning Of the Month: "+beginningOfMonth);
The code above yeilds:
beginning Of the Month: Sat Sep 01 2018 21:44:00 GMT+0300 (East Africa Time)
...
var endOfMonth = new Date();
endOfMonth.setMonth(8, 30);
console.log("end Of the Month: "+endOfMonth);
The code above yields:
end Of the Month: Sun Sep 30 2018 21:44:00 GMT+0300 (East Africa Time)
...perfect so far, however in the query below:
Meteor.users.find({ createdAt: { $gte: currentDate }}, { createdAt: { lte: endMonth }}, { "services.google.email": { $exists: true } } ).fetch();
The query above yields the below. NOTE that the createAt dates lay outside what the query queries.
[{…}]
0:
createdAt: Thu Oct 04 2018 14:54:33 GMT+0300 (East Africa Time)
profile: {name: "Sir ProgrammerAllot"}
services: {google: {…}, resume: {…}}
_id: "2trR7WxnqKJuuipG8"
__proto__: Object
length: 1
__proto__: Array(0)
How do I modify the query to only show the users created in the database between 1st of september and the last day of September?
Looking forward to your response.
You need to put all your query terms into a single object (and use $lte instead of lte):
Meteor.users.find({
createdAt: { $gte: currentDate, $lte: endMonth },
"services.google.email": { $exists: true }
}).fetch();
Putting the "query terms into a single object" as suggested by #JohnnyHK, and wrapping every query (criteria) statement helped in making the overall query work.
Find below the working solution:
Meteor.users.find(
{createdAt: { $gte: beginningOfMonth, $lte: endOfMonth }},
{"services.google.email": { $exists: true }}
).count();

Convert a string into Date in a query to get data between two dates in MongoDB

collection data:
{
"UserId":ObjectId('55525252525252'),
"CreatedDate":"Fri Apr 01 2015"
},
{
"UserId":ObjectId('55525252525252'),
"CreatedDate":"Fri Apr 01 2016"
},
{
"UserId":ObjectId('55525252525252'),
"CreatedDate":"Fri Apr 01 2017"
}
db.getDate.find({"UserID":ObjectId('55525252525252'),"CreatedDate":{"$gte":new Date('Fri Apr 01 2015'),"$lte":new Date('Fri Apr 01 2017')}})
when I execute this country it not returning data as expected
How to convert string into date to perform the give query
You should store date in Date format, you can convert your existing CreatedDate field using :
db.getDate.find().forEach(function(doc) {
doc.CreatedDate = new Date(doc.CreatedDate);
db.getDate.save(doc);
});
In your query build Date() with new Date("<YYYY-mm-dd>")
db.getDate.find({
"CreatedDate": {
"$gte": new Date('2015-04-01'),
"$lte": new Date('2017-04-01')
}
})

SUM the results of GROUP BY whilst using the IN operator with PostgreSQL

My query:
SELECT "Tracks"."PageId", date_trunc('month', "Tracks"."createdAt") AS month
FROM "Tracks"
WHERE "Tracks"."PageId" IN (1,2,3)
GROUP BY month, "Tracks"."PageId"`)
However, this yields:
[ { PageId: 30, month: Thu Sep 01 2016 01:00:00 GMT+0100 (BST) },
{ PageId: 29, month: Thu Sep 01 2016 01:00:00 GMT+0100 (BST) },
{ PageId: 31, month: Thu Sep 01 2016 01:00:00 GMT+0100 (BST) },
{ PageId: 29, month: Sat Oct 01 2016 01:00:00 GMT+0100 (BST) } ]
What's the best approach to also get the SUM of each PageId, ie. there were 3 of PageId 29 in October 2016, and 2 in September...

Mongodb Sum field within date range and other filters

Assuming I have the following document structure in my mongodb:
{
_id: "tMSfNq9JR85XDaQe5"
customerid: "QDGvBQhS6vYgZtnRr"
employeeid: "QDGvBQhS6vYgZtnRr"
date: Sun Dec 07 2014 19:50:21 GMT+0800 (HKT)
projectid: "S83NEGHnrefvfASrf"
hours: 2
}
Is it possible to get total hours spent on a specific project and customer, grouped by employee and date, while querying data within specific date range, so that the output will be for example like:
{ "projectid":"XXX", "date":"Dec 1, 2014", "employeeid":"AAA", "totalHrs":"20" }
{ "projectid":"XXX", "date":"Dec 1, 2014", "employeeid":"BBB", "totalHrs":"11" }
{ "projectid":"XXX", "date":"Dec 2, 2014", "employeeid":"AAA", "totalHrs":"3" }
{ "projectid":"XXX", "date":"Dec 2, 2014", "employeeid":"BBB", "totalHrs":"5" }
{ "projectid":"XXX", "date":"Dec 2, 2014", "employeeid":"CCC", "totalHrs":"18" }
Thanks
Hi as per my understand I think you want to groups on projectid and employeeid as looking to your desired output so I think below aggregation may work in this case
db.collectionName.aggregate(
{"$group":{"_id":{"projectId":"$projectid","employeeId":"$employeeid","date":"$date"},
"totalHrs":{"$sum":"$hours"}}},
{"$project":{"projectid":"$_id.projectId",
"date":"$_id.date","employeeid":"$_id.employeeId",
"totalHrs":"$totalHrs",
"_id":0}}
)
You need to group by projectid,date,employeeid
db.collectionname.aggregate({"$project":{"projectid":1,"date":1,"employeeid":1,"totalHrs":1}},
{"$group":{"_id":{"$projectId":"$projectid","date":"$date","employeeId":"$employeeid"},
"totalHrs":{"$sum":"$hours"}}})

Mongodb shell new Date(string)

I am experiencing a very weird issue with MongoDB shell version: 2.4.6. It has to do with creating ISODate objects from strings. See below for a specific example.
Why does this not work.
collection.aggregate({$project: {created_at: 1, ts: {$add: new Date('created_at')}}}, {$limit: 1})
{
"result" : [
{
"_id" : ObjectId("522ff3b075e90018b2e2dfc4"),
"created_at" : "Wed Sep 11 04:38:08 +0000 2013",
"ts" : ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ")
}
],
"ok" : 1
}
But this does.
collection.aggregate({$project: {created_at: 1, ts: {$add: new Date('Wed Sep 11 04:38:08 +0000 2013')}}}, {$limit: 1})
{
"result" : [
{
"_id" : ObjectId("522ff3b075e90018b2e2dfc4"),
"created_at" : "Wed Sep 11 04:38:08 +0000 2013",
"ts" : ISODate("2013-09-11T04:38:08Z")
}
],
"ok" : 1
}
The short answer is that you're passing the string 'created_at' to the Date constructor. If you pass a malformed date string to the constructor, you get ISODate("0NaN-NaN-NaNTNaN:NaN:NaNZ") in return.
To properly create a new date you'd have to do so by passing in the contents of 'created_at'. Unfortunately, I don't know of a way to run a date constructor on a string using the aggregation framework at this time. If your collection is small enough, you could do this in the client by iterating over your collection and adding a new date field to each document.
Kindof similar problem:
I had documents in MongoDB with NO dates being set in, and the DB is filling up so ultimately I need to go in and delete items that are older than one year.
I did sortof have date in a crappy human readable string format. which I can grab from '$ParentMasterItem.Name';
Example: '20211109 VendorName ProductType Pricing Update Workflow'.
So here's my attempt to pull out the dates (via substring parsing) -- (thankfully I do happen to know that every one of the 100K documents has it set the same way)
db.MyCollectionName.aggregate({$project: {
created_at: 1,
ts: {$add: {
$dateFromString: {
dateString: {
/* 0123 (year)
45 (month)
67 (day)
# '20211109 blahblah string'*/
$concat: [ { $substr: [ "$ParentMasterItem.Name", 0, 4 ]}, "-",
{ $substr: [ "$ParentMasterItem.Name", 4, 2 ]}, "-",
{ $substr: [ "$ParentMasterItem.Name", 6, 2 ]},
'T01:00:00Z']
}}}}}}, {$limit: 10})
output:
{ _id: 8445390, ts: ISODate("2022-12-19T01:00:00.000Z") },