I wanted to find data for 2014-08-01 from MongoDB collection. Date in MongoDB is in ISO format.I wrote below query, but it gives me very huge number which i suspect is not the data for 1 day. Can some one let me know what is wrong with query.
sd is the key
db.history.count({sd:{$gte: new Date("2014-08-01")},sd:{$lt:new Date("2014-08-01")}})
Ranges can be specified using $gte and $lt in the same document portion:
db.history.count({ "sd": {
"$gte": new Date("2014-08-01"), "$lt": new Date("2014-08-02")
}})
Otherwise the argument are considered to be separate and a logical "and" condition. But really since you are using the same "key" in your "sd" field, this is not allowed in a JSON/BSON document and violates the "unique" keys rule for hash structures in general. So one condition overwrites the other and only one is applied.
That is why your result is wrong. Use as shown above instead.
await model.find(
{
$or:
[
{
createdDate:
{ $gte: new Date(startDate), $lte: new Date(endDate) },
},
{
createdDate:
{ $gte: new Date(startDate), $lte: new Date(endDate).setDate(new Date(endDate).getDate() + 1) },
},
],
},
)
Please assign value to startDate and endDate. The above example will help to find different data from different date as well as the same date
for example if your trying to fetch data from '2020-06-22' to '2020-07-02' you will get data from this date range, other your are trying to fetch data on the same date this code will work that mechanism also
Thank you
Related
Here in provided aggregation pipeline, I need to compare a field which consists of previous date and time column called "HardStopDaysDate" with current date and time in mongo. I am using $$NOW itself here, but I am not able to see output, Can anyone please identify and help me what mistake I did.
db.customs.aggregate(
{
"$match": {
"Date": {
"$lt": "$$NOW"
},
"Status": {
"$ne": "Completed"
},
"$or": [
{
"Verification": null
},
{
"Verification": {
"$ne": 1
}
}
]
}
})
If I remove "$$NOW" then I am able to see result. But this comparison have to be done must and need to show desired result.
Here, I have to compare "Date" with current date and time so I am using "$$NOW". The query is working fine but not able to see any records. The filtered records have to be displayed which records are less than "Date".
Giving Sample records how "Date" is there in db.
[{"Date":2022-02-18 21:27:00}]
Can anyone please help me on this to get records while comparing with "$$NOW"
I have several documents on MongoDB collection that were created with an invalid date value and have it currently as:
"UpdateDate " : Date(-62135596800000)
I want to filter those documents, but my query is not returning any data:
db.MyCollection.find({UpdateDate : Date(-62135596800000)})
How can I filter my collection to retrieve those documents?
The problem with your query is that you need to build a proper Date object. This may be different depending on what languaje or drivers are you using to query, but in JS just using new Date() should work.
db.MyCollection.find({UpdateDate : new Date(-62135596800000)})
If you cant reproduce what the value need to be , luckily the date when you have inserted the document for the first time you can extract and update from the document _id as follow:
db.getCollection('MyCollection').update({ UpdateDate : new Date(-62135596800000)
},
[
{ "$set": { "UpdateDate": { $toLong: { $toDate: "$_id" }}}}
],
{ "multi" : true}
)
This is with the assumption that you havent customized the default _id
I Have a mongodb with objects like this:
{
"_id" : "7XXXXXXXXXX",
"apps" : [
{
"id" : "e0d538e0df9a345e",
"os" : "android",
"token" : "f1zp-VSi7Ec:APA91bEAbfH8nMeVidkIjPrJ28WHRFDy-BhvKCQdDSdCYsylUzET9GjbPHjofCrr1NMQurinMCI4fuiF7VWNPXne-80op_h0MloK217kc1zKptdo9FTgAH5R932uDphcyB1xQ27-AFdR",
"version" : "3.2.1",
"build" : "8115680e",
"timestamp" : NumberLong(1571740696818)
}
]
}
How i can select objects older certain date using timestampin my case, for example older 3 month?
You can use $toDate operator in aggregation to do the desired operation,
I hope you are using mongo version 4.0+
$toDate is supported in mongo version 4.0 and on
let selectedDate = new Date();
selectedDate.setDate(d.getDate()-30); //subtracting 30 days from today's date
db.collection("your_collection_name").aggregate({$unwind:{ path: "$apps"}},
{$addFields: { dateValue: {$toDate: "$apps.timestamp" }}},
{$match: { dateValue: {$lte: selectedDate }}},
(err, result) => {
//perform your desired operations
});
Explanation:
basically, I am first unwinding apps array, which will result in having a separate document of each entry in apps.
Then operate on the timestamp field in each document, and convert it into a proper date with $toDate.
Then in the next stage apply your filter with $match.
UPDATE (from comments):
as you are using mongo version 3.2 the above solution will not work.
then I think, you can opt for another approach here:
Query all your documents in this particular collection, find the proper date from the timestamp field.
Update each document with a new field which will now have the value of computed date from the above step, and save it.
I suggest you write a migration script for the above two steps.
Make sure when inserting a new document, you already add this newly computed date field.
Then you can have simple query like:
db.collection("your_collection_name").find({"app.newDateField": {$lte: {selectedDate }}},
{ "apps.$": 1},
(err, result)=>{
})
I tried to search MongoDB id in a particular date range using MongoDB query. but it's throwing an error can anyone give any suggestion.
Mongo DB Data
[{
id:1,
full_name:"naveen",
date:"2019-11-02"
},{
id:2,
full_name:"naveen123",
date:"2019-11-04"
}]
mongodb query
db.collection.find({id:1,date:{ '$gte': 2019-11-02,
'$lt': 2019-11-06 }})
You are missing commas for date values in the query.
Modify your query like below:
db.collection.find({id:1, date:{ "$gte": "2019-11-02", "$lt": "2019-11-06" }});
This is how you may like to do it, but not me.
There are some changes I suggest you should do if you are not already doing it.
1. If you are storing dates as strings in DB, don't do that.
use proper Date format, both while querying and storing.
2. use below format of query:
db.collection.find({id:1, date:{ /* cond1 */ },
date: { /* cond2 */ }
});
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)