Query to get data from mongodb using ObjectId ("xxxxxxxxx").GetTimestamp() - mongodb

I am starting in the world of mongodb.
I have the following question:
I want to find the items that were posted from date x. In the records I have no date but I can get it from this statement:
ObjectId ("5ffdc390fdd1596ca5870bec"). GetTimestamp ()
whose result is: ISODate ("2021-01-12T15: 43: 12Z")
How could I create a query that returns all the records that were created from a given date, for example from 2021-01-12?
Thank you very much.!

The mongo Shell is an interactive JavaScript interface to MongoDB, so the solution by Leftium should work.
function objectIdWithTimestamp(timestamp) {
/* Convert string date to Date object (otherwise assume timestamp is a date) */
if (typeof(timestamp) == 'string') {
timestamp = new Date(timestamp);
}
/* Convert date object to hex seconds since Unix epoch */
var hexSeconds = Math.floor(timestamp/1000).toString(16);
/* Create an ObjectId with that hex timestamp */
var constructedObjectId = new ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId
}
/* Find all documents created between Jan 12th, 2021 and Jan 13th, 2021 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('2021/01/12'), $lt: objectIdWithTimestamp('2021/01/13') } });

You can query it directly:
db.collection.find({
$expr: {
$gte: [ {$toDate: "$_id"}, ISODate("2021-01-01T00:00:00Z") ] }
}
)
Usually I prefer the moment.js library, could be this for example:
db.collection.find({
$expr: {
$gte: [ {$toDate: "$_id"}, moment().startOf('day').subtract(3, 'days').toDate() ] }
}
)

Related

How to convert string to ISODate in mongodb and compare it with $$NOW

Here, In my mongo collection, the date type column data is stored as string. I have a view where I need to compare this date with current date and time $$NOW. Since my date is stored as string. The query is getting executed but not getting compared. I tried to convert this string to date type but the data changed like this 2022-05-23 1:28:36 quotes were gone. Tried to run same query, but getting an error.
sample data:
[{oldDate:"2022-05-23 1:28:36"}]
My query:
db.collection.aggregate([
{
"$match": {
$expr: {
$lt: [
"$oldDate",
"$$NOW"
]
}
}
}
])
If the data in db is in the form of ISODate("2022-05-23 1:28:36") then this query is working. But the actual data in my db for this column is in the form of string. Can anyone help me to convert this to ISODate() through code itself and make comparison work.
Use $toDate operator to convert date string to date.
db.collection.aggregate([
{
"$match": {
$expr: {
$lt: [
{
$toDate: "$oldDate"
},
"$$NOW"
]
}
}
}
])
Sample Mongo Playground

MongoDB query based on date plus time

i've to run a query like this (sql) in MongoDb 4:
SELECT * FROM log WHERE DATE_ADD(created_at, INTERVAL 2 HOUR) < NOW()
Basically, I want to find all the documents, in the PENDING state, whose creation date PLUS TWO HOURS is less than now .. Let me explain: I want to find all the documents in the PENDING state that have been in PENDING for more than two hours.
I feel stupid, but I am failing to do this with MongoDb.
I also created a playground:
https://mongoplayground.net/p/4bifqiX2KMJ
Can you help me?
You can add hours in ISO date using $add, convert string date to ISO date using dateFromString,
let date = new Date();
db.collection.find({
status: "pending",
$expr: {
$lt: [
{
$add: [
// convert string date to ISOdate, if its already then use only "$inserted_at"
{ $dateFromString: { dateString: "$inserted_at" } },
// add milliseconds
7200000 // (60*60*2000)
]
},
date
]
}
})
Playground
Or subtract from current date and then compare the condition,
let date = new Date();
date = new Date(date.getHours()-2); //subtract 2 hours
db.collection.find({
status: "pending",
$expr: {
$lt: [
{ $dateFromString: { dateString: "$inserted_at" } },
date
]
}
})
Playground

Get all records with specified properties between a certain date range

I am passing in two dates formatted as MM-DD-YYYY which is a date range. I need to query all records within that range and include specified fields. I've had no luck.
Part of a record in Mongo:
{
"_id": "some ID",
"date": {
"$date": "2015-06-26T13:02:12.121Z"
},
Query:
var Start = '09-07-2015'
var End = '09-14-2015'
If I do:
var query = Order.find({
date : {
$lt : End,
$gt : Start
}
});
I get the full document within the week ranges as expected. However, I want to specify the fields to return rather than full document. So I've tried using grouping and project to specify those fields:
var query = Order.aggregate(
{
$match :
{
date: {
$gte: start,
$lt: end
}
},
$group:
{
cust_ID: '$request.headers.customer_id',
wholesaler_ID: '$request.headers.wholesalerID'
}
}
);
Likewise: I've also tried it using project to get the results I want. I thought maybe it won't match on a date string like 09-07-2015, so I included the ISO date directly. Still no luck... the query comes back undefined or empty:
var query = Order.aggregate(
{
$project:
{
date: 'date',
cust_ID: '$request.headers.custID',
wholesaler_ID: '$request.headers.wholesalerID'
}
},
{
$match :
{
date: {
$gte: "2014-12-09T21:02:56.872Z",
$lt: "2015-12-09T21:02:56.872Z"
}
}
}
);
var query = Order.find({
date : {
$lt : End,
$gt : Start
}}, {cust_ID:1, wholeseller_ID:1}
);
This will work.
I just tested this using Robomongo
db.getCollection('offerdb').find({time_posted:{$gt: '2015-10-21T21:40:04+05:30', $lte:'2015-12-14T05:53:14+05:30'}},{_id:1, merchant_id:1})
Works like a charm for me.
Try this command in mongo shell
use dbname
db.collection_name.find({date: {$gte: ISODate('2015-09-07 00:00:00'), $lte: ISODate('2015-09-14 23:59:59.999999')}},{'cust_ID':1,'_id':0,'wholeseller_ID':1})

Get data between two dates mongo

I need to query the data between two dates.
I was pushing data into mongo where dates are in the format : 13-10-2015 15:08:22
Is there a way to do it?
Can't i tell mongo to compare these as dates with format explicilty mentioned
You can use the generic $gte and $lte query modifiers when dealing with Dates in mongo
{ $gte: startDate, $lte: endDate }
should work just fine (where endDate and startDate are Javascript Date objects)
You can use aggregate function in mongodb.
You can get dates using this :
let todayDate = new Date();
let beforeDate = new Date();
beforeDate.setDate(beforeDate.getDate() - 15);
[Here 15 is days. It will subtract 15 days from current date].
TableName.aggregate([
{
"$match":
{
"Date":
{
"$lte": todayDate,
"$gte": beforeDate
}
}
}
])
let today = new Date();
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
{
$match: {
createdAt: {
$gte: sevenDaysAgo,
$lte: today,
},
},
},

Why are dates in match aggregate query being ignored?

I'm trying to run an aggregation statement in my mongo db. I have a document whose structure is (at least) as follows:
{
"_id": ObjectId,
"date": ISODate,
"keywordGroupId": NumberLong,
"ranking": NumberLong,
}
I would like to run an aggregation statement that aggregates the 'ranking' field for a given 'keywordGroupId' and a given 'date' interval.
I have been trying with the following aggregate command:
{
aggregate : "KeywordHistory",
pipeline : [
{ $match: { keywordGroupId: 75 , "$date": {$gte: ISODate("2013-01-01T00:00:00.0Z"), $lt: ISODate("2013-02-01T00:00:00.0Z")}} },
{ $group: { _id: { null }, count: { $sum: "$ranking" } } }
]
}
This command executes without errors and returns a result. If I try to change the value for the 'keywordGroupId' field, the command returns a different value, so I assume that the $match statement works for that field (NumberLong). Though, if I change the 'date' range and I specify a time interval for which I don't have any data in the database, it still returns a result (I would actually expect an empty result set). So I have to assume that the $match statement is ignoring the date interval specified.
Can anyone help me with this point?
Remove the $ prefix on the $date field of your $match:
{ $match: {
keywordGroupId: 75,
date: {$gte: ISODate("2013-01-01T00:00:00.0Z"), $lt: ISODate("2013-02-01T00:00:00.0Z")}
}},
You only use the $ prefix when the field name is used in a value, not as a key.
Sometimes ISodate does not works . so in Case if you want to match date using only "one" date the best way is:---
ex:-- Let a schema be:---
var storeOrder = new Schema({
store_name:{type:String, required:true},
date :{type:Date ,default:moment(new Date()).format('YYYY-MM-DD')},
orders : [{
vegetable : String,
quantity : Number,
price:Number
}]
});
mongoose.model('storeorder',storeOrder);
now to aggregate by matching date :--
storeOrder.aggregate([$match:{date :new Date("2016-12-26T00:00:00.000Z")} ])
**It is must to use new Date("2016-12-26T00:00:00.000z") instead of Date("2016-12-26T00:00:00.000z") because Date(your_date) !== new Date(your_date).
THANK YOU
The aggregate expects a Javascript Date Object and doesn't work otherwise.
new Date();
new Date(year, month, day);
Please note the month start with 0 and not 1 (Your January is 0 and December 11)