I'm trying to insert a record in mongo that expires in sometime.
getMessagesCollection().ensureIndex(new BasicDBObject("createdAt", 1), new BasicDBObject("expireAfterSeconds", 10));
I insert my data like this
Map map = new HashMap();
map.put("_id", mongoMessage.getObjectId());
// Other code
map.put("createdAt", new Date());
getMessagesCollection().insert(convertToDBObject(map))
the field createdAt is a date and before inserting the object looks like this
{ "_id" : "551bf9b72bea951ecf53fc5f" , "createdAt" : { "$date" : "2015-04-01T09:59:19.723Z"} , ...}
But the record is not getting deleted. Can someone tell me what I'm doing wrong?
Looks like you're incorrectly creating the date.
Check out how it's done here
Date now = new Date();
BasicDBObject time = new BasicDBObject("ts", now);
Related
I have a document in my collection like
{
"_id" : ObjectId("5e3aaa7cdadc161d9c3e8014"),
"carrierType" : "AIR",
"carrierCode" : "TK",
"flightNo" : "2134",
"depLocationCode" : "DEL",
"arrLocationCode" : "LHR",
"depCountryCode" : "DELHI",
"arrCountryCode" : "LONDON",
"scheduledDepDateTime" : ISODate("2020-02-05T00:30:00Z")
}
{
"_id" : ObjectId("5e3aaacddadc161d9c3e8015"),
"carrierType" : "AIR",
"carrierCode" : "TK",
"flightNo" : "2021",
"depLocationCode" : "DEL",
"arrLocationCode" : "LHR",
"depCountryCode" : "DELHI",
"arrCountryCode" : "LONDON",
"scheduledDepDateTime" : ISODate("2020-02-05T00:00:00Z")
}
I am putting criteria like
Criteria criteria = new Criteria();
criteria = criteria.and("carrierCode").is("TK");
String from = "2020-02-05";
String to = "2020-02-05";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date toDate = dateFormat.parse(to);
Date fromDate = dateFormat.parse(from);
criteria = criteria.and("scheduledDepDateTime").gte(fromDate).lte(toDate);
But i am getting document only the field which have time 00 not both the document. I have two documents with that date but in response getting only one. I have tried so many things but not succeed. I want to compare only the date and ignore the time. Please help.
The from and to dates must be the lowest time and the highest time for that date, respectively; this will cover all the hours of the day.
For using the same field ("scheduledDepDateTime") with the $and operator you must use the Criteria's andOperator not the and (see AND Queries With Multiple Expressions Specifying the Same Field).
The updated code:
Criteria criteria = new Criteria();
criteria = criteria.and("carrierCode").is("TK");
String from = "2020-02-05 00:00:00";
String to = "2020-02-05 23:59:59";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:m:s");
Date toDate = dateFormat.parse(to);
Date fromDate = dateFormat.parse(from);
criteria = criteria.andOperator(where("scheduledDepDateTime").gte(fromDate), where("scheduledDepDateTime").lte(toDate)));
// Query qry = new Query(criteria);
// List<SomeClassName> result = mongoTemplate.find(qry, SomeClassName.class, "collection_name");
The ISODate in mongod is stored as an epoch timestamp with millisecond resolution.
dateFormat.parse is likely returning ISODate("2020-02-05T00:00:00.000Z"), which would be stored in the db as 1580860800000.
This effectively means your query is {scheduledDepDateTime:{$gte: 1580860800000, $lte: 1580860800000}}, so the only possible value that could satisfy the filter is ISODate("2020-02-05T00:00:00.000Z").
To get all documents with that date, you might try making your toDate be the following day, and use $lt instead of $lte.
As suggested by #prasad todate must be the lowest time and the highest time for that date I have to set time in todate field to 23:23:59 like this and it works.
public static Date convertToDate(final Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
I have around 30-40 records like the example before in my database and I'm looking to get the notifications that are less than 1 month old (from today's date). Is there a way in Mongo to get these results without having to pass in a today's date via JavaScript? Or if I do have to pass it in via JavaScript, how would I process this against my created date?
{
"_id" : ObjectId("48445b4dc72153e9ad7f3bfb"),
"notificationID" : "78723asd5-vnbb-xv31-afe0-fa9asf164e4",
"notification" : "Notification #1",
"created" : ISODate("2016-11-21T20:33:53.695Z")
}
Any help is appreciated, thanks.
MongoDB has its own Javascript interpreter so, unless your MongoDB server has a different date than your system, it knows the current date so you easily use simple Javascript to compute the value you're looking for using a regular Date object and use it in your query.
var d = new Date();
d.setMonth(d.getMonth() - 1); //1 month ago
db.data.find({created:{$gte:d}}); //change "data" for your collection's name
If you need a different date than your database's, I'm afraid you'll have to somehow pass it as a parameter.
const now = new Date()
const temp = new Date(now).setMonth(now.getMonth() - 6);
const priorSix = new Date(temp)
Table.find({"date" : {$gte: priorSix, $lt: new Date()}}, (err, tables) => {
if(err) throw new Error(err)
res.status(200).json(tables)
}).populate('foodList.item')
This code worked for me. It retrieves documents of the last 6 month :)
I have a field startTime in MongoDB collection that stores time in the following form:
2015-07-22 08:19:04.652Z
I would like to find all documents that has the startTime greater than or equal to yesterday's time(from exactly one day before). I tried using the $currentDate in the find query, but I was not able to make it work.
EDITED:
Sample Document:
{
"_id" : ObjectId("55af5241e4b0ec7c53360333"),
"startTime" : ISODate("2015-08-22T08:19:04.652Z"),
"sampleId" : "SS10"
}
EDITED 2: No aggregation framework allowed.
Compute the previous date first the pass it in find query.
In javascript:
var date = new Date();
date.setDate(date.getDate() - 1);
db.col.find({'startTime':{'$gte':date}})
MongoDB document sample is given below:
{
"_id" : ObjectId("5f2df113bdde22f1043g45gg"),
"cd" : 1395376406,
"dob" : 552026006,
"e" : "test#gmail.com",
"g" : "M"
}
I need query to get birthday list for today using dob(date of birth) field(timestamp).
Thanks in advance!
I am not sure how elegant my solution is, but it should work
var start = new Date();
start.setHours(0,0,0,0);
var end = new Date();
end.setHours(23,59,59,999);
db.collection.find({dob:{$gt:start.getTime(), $lt:end.getTime()}})
Since MongoDb doesn't have any inbuilt functions/operations to support parsing raw timestamps and extracting information from them, you need to do the operation by passing a custom java script function to the server and get it executed there. This function would be executed for each record though.
db.collection.find({$where:function(){
var recDate = new Date(this.dob);
var recDay = recDate.getDate();
var recMonth = recDate.getMonth();
var today = new Date();
var todayDate = today.getDate();
var todayMonth = today.getMonth();
return (recDay == todayDate && recMonth == todayMonth);
}});
The function simply checks if any record's day and month match today's day and month.
Although this works for timestamps, you should take advantage of MongoDBs ISODate data type whenever you store date information. This enables us to use various operators and functions on these fields. Moreover they would be faster. If your document had the below structure:
{
"_id" : "1",
"cd" : 1395376406,
"dob" : ISODate("2014-11-19T08:00:00Z"),
"e" : "test#gmail.com",
"g" : "M"
}
Where, the dob field is of ISODate type. You could easily do a aggregate operation to fetch the results.
var todayDate = ISODate().getDate();
var todayMonth = ISODate().getMonth();
db.collection.aggregate([
{$project:{"day":{$dayOfMonth:"$dob"},
"month":{$month:"$dob"},
"_id":1,"cd":1,"dob":1,"e":1,"g":1}},
{$match:{"day":todayDate,"month":todayMonth}},
{$project:{"cd":1,"dob":1,"e":1,"g":1,"_id":1}}
])
The above operation utilizes the functions and operations that are allowed on a ISODate field. Querying becomes a lot easier and better.
I am new to mongoDB. I have following code create collection and document But there is no timestamp field. Is there any way to insert created_on automatically in documents.
db.createCollection("countries"); //Created collection
db.countries.insert({"short_name":"AF","country_name":"Afganistan"}); //Created document
db.countries.find()
{ "_id" : ObjectId("53d1d5bcb8173a625961ff34"), "short_name" : "AF", "country_name" : "Afganistan" }
What I am really after is assigning a default "created_on" to my documents using Cake PHP. So how do you do that?
Mongodb will not insert anything automatically except the '_id' field. You can get the time of insertion from '_id' field like this -
ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()
The result would look something like this -
ISODate("2012-10-15T21:26:17Z")
If you want to insert created_on field yourself then -
If you are on mongo shell then new Date() would insert the current time.
db.mycollection.insert({ 'created_on' : new Date() })
And if you want to use raw PHP then -
$collection->save(array("created_on" => new MongoDate()));
Hope this helps :-)
This worked for me:
echo (new MongoDB\BSON\ObjectId("612e10058e19a6074399f7dd"))->getTimestamp();