How to check the particular data in range using mongodb query? - mongodb

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 */ }
});

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

MongoShell db query of string date is not working

I am trying to query my database on the date_recorded field, but the query give zero results. I'm using the MongoShell and have also tried it in Compass.
I've tried variations of $eq with ISODate and Date:
db.my_collection.find({ "date_recorded": { "$eq": new ISODate("2017-06-09T01:27:33.967Z") }}).count()
I have also tried variations of $gte with ISODate and Date:
db.my_collection.find({ "date_recorded": { "$gte": new Date("2017-06-09T01:27:33.967Z") }}).count()
Record is in the db, notice the highlighted field
Like #JohnnyHK said, the date_recorded is a string. To make a comparison, we either need to convert date_recorded to a date or compare is with a string.
The following queries can get us the expected output:
db.my_collection.find({
"date_recorded": {
$eq:"2017-06-09T01:27:33.967Z"
}
}).count()
db.my_collection.find({
$expr:{
$eq:[
{
$toDate:"$date_recorded"
},
new ISODate("2017-06-09T01:27:33.967Z")
]
}
}).count()

MongoDB query to update date field in an document with another date field plus 1 day

I am trying to update a date field (say nextChargeDate) in multiple documents in a collection with another date field (say currentTermEndDate) in the same document incrementing the currentTermEndDate by 1 day.
Here's the update function I have written:
db.some_collection.updateMany(
{$or: [{_id: ObjectId('5c3e62ef2e9c4e0008f4749f')}, {_id: ObjectId('5c3e635a2e9c4e0008f47852')}, {_id: ObjectId('5c3e63a12e9c4e0008f47ab9')}]},
{
$set: { **nextChargeDate: new Date({$add: [ "currentTermEndDate", 1*24*60*60000 ]}**) }
}
)
Here's the update looks like in Mongo:
currentTermEndDate:2019-04-04 23:59:59.999
nextChargeDate:1969-12-31 18:00:00.000
It would be very helpful if someone can help with a solution to achieve the desired result which would be:
currentTermEndDate:2019-04-04 23:59:59.999
nextChargeDate:2019-04-05 23:59:59.999
Thanks in advance.
You need to take a date as ISODate("dateField").getTime(). Try below query:-
{$or: [{_id: ObjectId('5c3e62ef2e9c4e0008f4749f')}, {_id: ObjectId('5c3e635a2e9c4e0008f47852')}, {_id: ObjectId('5c3e63a12e9c4e0008f47ab9')}]},
{
$set: { "nextChargeDate": new Date(ISODate("currentTermEndDate").getTime()+ 1*24*60*60000) }
}

MongoDB update collection's data

I try to update an MongoDB data by using this code:
db.medicines.update({"_id":"586a048e34e5c12614a7424a"}, {$set: {amount:'3'}})
but unfortantly the query does not recognize the selector "_id":"586a048e34e5c12614a7424a", even if its exists.
Its succsed when I change the key to another like: name,rate and etc..
there is a special way to use update with _id parameter?
Thanks a head.
_id will be the unique ObjectId that mongodb generates for every document before inserting it. The query dint work because _id is an ObjectId and "586a048e34e5c12614a7424a" is a String. You need to wrap _id with ObjectId().
If you're using mongodb query
db.medicines.update({
"_id": ObjectId("586a048e34e5c12614a7424a")
}, {
$set: {
amount: '3'
}
});
If you are using mongoose. You can use findByIdAndUpdate
db.medicines.findByIdAndUpdate({
"_id": "586a048e34e5c12614a7424a"
}, {
$set: {
amount: '3'
}
});

Find data for specific date in mongodb

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