Looking for function similar to "BETWEEN" in MongoDB - mongodb

I need to get all records from MongoDB collection "employee" where joining_date is between current_date and current_date + 5 days. I couldn't find anything similar to BETWEEN operator in MongoDB documentation. Below query works fine in Google BigQuery. Looking for similar solution in MongoDB.
select * from employee where joining_date BETWEEN current_date() and DATE_ADD(current_date(), interval 5 DAY);

The $gt and $lt Comparison Query Operators can be used to find matches within a range of dates. Here's one approach.
db.employee.find({
"joining_date": {
$gt: new Date(),
$lt: new Date(new Date().setDate(new Date().getDate() + 5))
}
})

Related

MongoDB 4.4: Compare particular date with an interval of other date

Basically what I want to do is to compare that the difference between 2 date is less than 1 year, i.e. scheduled_end < scheduled_start + 1 year
I'm trying to use the following expression, but it does not seem valid:
scheduled_end: {
$lt: {
$add: [scheduled_start, 365*24*60*60000 ]
}
}
How to fix it?
I'm using MongoDB 4.4, so $dateAdd is not available in this version.

Mongodb query to get document count for each month of a specific year

I have a time field as below in my collection.
"time" : NumberLong(1531958400000)
I first want to query documents by the current year(using $match) and then get the document count for each month.
I have managed to match the year using the below query.
db.myCollection.aggregate([
{$project: {
year: { "$year":{"$add":[new Date(0),"$time"]}}
}
},
{$match: {year: 2021}}
])
How can I write a mongodb query for the mentioned scenario?
Thanks in advance!
You can do following:
parsed the timestamp using $date
compare the parsed date field with current year
$group by $month value to get the count
Here is the Mongo playground for your reference.

Aggregating last n days in MongoDB

I'm trying to build a query in MongoDb (to be run with pymongo) to get a sum by groups for the last 30 days. I'm really struggling to combine both aggregate function and date differences. Tne SQL equivalent of the query would be:
SELECT item, sum(volume) from table
where date >= DATEADD(DAY, -30, now())
group by item
Can anyone help?
This is quite simple, first you want to match the matching documents by their date field and then use $group to calculate the sum.
First what we need for the code:
import pymongo
from datetime import date, timedelta, datetime
connection = pymongo.MongoClient("connection url")
collection = connection["db_name"]['collection_name']
Main Aggregation:
thirty_days_ago = date.today() - timedelta(days=30)
results = list(collection.aggregate([
{
"$match": {
"date": {"$gt": thirty_days_ago }
}
},
{
"$group": {
"_id": "item",
"sum": {"$sum": "$volume"}
}
}
]))
I had to guess some of the fields names as you did not provide a schema but you should be able to easily adapt it to your needs.

Best way to get documents in specific timeframe MongoDB

I am creating a script that would run after every x minutes and needs to gather data from MongoDB by timestamps.
For example, how would I match the documents with aggregation that have a timestamp in the following timeframe:
start_time = current_time - 60 min
end_time = start_time + 30 min
And I would need to get all the documents that stay within that time frame.
The MongoDB objects have ISODate timestamps on them.
Thanks!
You can create date objects in mongo shell like so:
db.getCollection('order').aggregate([
{
$match : {
start_time : {$gte : new Date(ISODate().getTime() - 1000 * 60 * 60)},
end_time : {$lte : new Date(ISODate().getTime() + 1000 * 60 * 30)}
}
}
...
])
You can use this in aggregate but also in normal find queries.
Note I wrote this without testing, so it might have syntax errors..
db.collection.find({"createdAt": { $gt: new Date('2017-04-25')},"updatedAt":{$lt:new Date('2017-06-25')}})
updatedAt and createdAt are the feilds I have taken at the time of designing the schema by timestamp. You could give feilds according to you design.
the find query would be little better than aggregate in this case as no complex functions have to be performed

Query mongo on timestamp

I want to query Mongo based on timestamp. Follwing is the field in mongo.
"timestamp" : "2016-03-07 11:33:48"
Books is the collection name and below is my query for time period of 1 minute:
db.Books.find({"timestamp":{$gte: ISODate("2016-03-07T11:33:48.000Z"), $lt: ISODate("2016-03-07T11:34:48.000Z")}})
Also is there any alternative like I don't have to give greater and lower limit on timestamp. But query based time interval mentioned. Something like, if present timestamp is TS = "2016-03-07T11:33:48.000Z" then query should be between TS and TS + 1 minute rather than explicitly mentioning timestamp. Something like adding 1 minute to present timestamp
db.Books.find({"timestamp":{$gte: "2016-03-07 11:33:48", $lt: "2016-03-07 11:34:48"}})
ISODate is not required here