convert timestamp to ISO date in Mongodb version 2.4 - date

I have mongodb version 2.4.10 installed. The structure of the document is :-
{
"_id" : ObjectId("5d15f245f4dda1e055091ae1"),
"name" : "test site service",
"starFromTimestamp" : NumberLong(1559275200),
"toTimestamp" : NumberLong(1561867200),
"uuid" : "ssg-5d15f245f2893825813309"
}
I excuted the following code in Mongo shell in order to convert timestamp to ISODate
db.servicesitegroup.find().forEach(function(doc) {
doc.startISODate=new Date(doc.starFromTimestamp);
db.servicesitegroup.save(doc);
})
The document got updated and the resultset looks like:-
{
"_id" : ObjectId("5d15f245f4dda1e055091ae1"),
"name" : "test site service",
"starFromTimestamp" : NumberLong(1559275200),
"toTimestamp" : NumberLong(1561867200),
"uuid" : "ssg-5d15f245f2893825813309",
"startISODate" : ISODate("1970-01-19T01:07:55.200Z")
}
If I use the timestamp converter, then the value of 1559275200 amounts to Friday, May 31, 2019 4:00:00 AM . Why is the timestamp not being converted to the correct value? Can anyone guide me here.

I needed to multiply the timestamp value with 1000 .
db.servicesitegroup.find().forEach(function(doc) {
doc.startISODate=new Date(doc.starFromTimestamp * 1000);
db.servicesitegroup.save(doc);
})
The code above gives me the correct output.

Related

Problem with matching date-time fields using MongoDB Spring Data Aggregation

Just want to do a MatchOperation on date in long format (date in seconds) in MongoDB
The fromDate and toDate Variables are with data type as long.
It's divided with 1000 to get the data in seconds format and not in milliseconds.
long fromDate = new Date().getTime()/1000;
The datetime field format is in mongo Document
"datetime" : NumberInt(1595745447),
MatchOperation matchDate = Aggregation.match(Criteria.where("datetime")
.gte(fromDate)
.lte(toDate));
the aggregation formed using this is
db.some_collection.aggregate([{ "$match" : { "datetime" : { "$gte" : { "$numberLong" : "1595356200"}, "$lte" : { "$numberLong" : "1595375999"}}}}])
But its not working. It's giving 0 results.
But when the same is just modified (as shown bellow) a bit manually by jus removing
"$numberLong"
it's giving results and Filters as expected.
db.some_collection.aggregate([{ "$match" : { "datetime" : { "$gte" :1595356200, "$lte" : 1595375999}}}])
Can any one help me out with this?
Thanks in advance.
There is a syntax error. NumberLong is a function not an operator.
Refer
Change
{ "$numberLong" : "1595356200"},
To
NumberLong("1595356200")

MONGODB - cast type of every object in array of objects

I have MongoDB Collection where some documents have arrays of objects. One of the fields of this objects is timestamp.
The problem is that historically some of timestamp values are Strings (e.g. '2018-02-25T13:33:56.675000') or Date and some of them are Double (e.g. 1528108521726.26).
I have to convert all of them to Double.
I've built the query to get all the documents with the problematic type:
db.getCollection('Cases').find({sent_messages: {$elemMatch:{timestamp: {$type:[2, 9]}}}})
And I also know how to convert Date-string to double using JS:
new Date("2018-02-18T06:39:20.797Z").getTime()
> 1518935960797
But I can't build the proper query to perform the update.
Here is an example of such a document:
{
"_id" : ObjectId("6c88f656532aab00050dc023"),
"created_at" : ISODate("2018-05-18T03:43:18.986Z"),
"updated_at" : ISODate("2018-05-18T06:39:20.798Z"),
"sent_messages" : [
{
"timestamp" : ISODate("2018-02-18T06:39:20.797Z"),
"text" : "Hey",
"sender" : "me"
}
],
"status" : 1
}
After the update it should be:
{
"_id" : ObjectId("6c88f656532aab00050dc023"),
"created_at" : ISODate("2018-05-18T03:43:18.986Z"),
"updated_at" : ISODate("2018-05-18T06:39:20.798Z"),
"sent_messages" : [
{
"timestamp" : 1518935960797.00,
"text" : "Hey",
"sender" : "me"
}
],
"status" : 1
}
As per your question, you are trying to fetch the record first.
db.getCollection('Cases').find({sent_messages: {$elemMatch:{timestamp: {$type:[2, 9]}}}})
Then convert date in JS:
new Date("2018-02-18T06:39:20.797Z").getTime()
And then this is an update query:
db.getCollection('Cases').updateOne({_id:ObjectId("6c88f656532aab00050dc023")}, { $set: { "sent_messages.$.timestamp" : "218392712937.0" }})
And if you want to update all records then you should write some forEach mechanism. I think you have already this implemented.
Hope this may help you.
Finally I just do it with JS code that can be run in mongo console:
db.getCollection('Cases').find({sent_messages: {$elemMatch:{timestamp: {$type:[2, 9]}}}}).forEach(function(doc) {
print('=================');
print(JSON.stringify(doc));
doc.sent_messages.forEach(function(msg){
var dbl = new Date(msg.timestamp).getTime();
print(dbl);
msg.timestamp = dbl;
});
print(JSON.stringify(doc))
db.Cases.save(doc);
} )
Thanks all for your help!

Use $lte for datetime querying is not working

I want to query data by using datetime that less than 15:00 in 2016-01-14 but it is not working.
Here is my example collection
{
"_id" : ObjectId("5697528237b79c198c94ad1a"),
"actionName" : "touchMove",
"timeStamp" : ISODate("2016-01-14T14:47:13.596Z")
}
{
"_id" : ObjectId("5697528237b79c198c94ad16"),
"actionName" : "touchDown",
"timeStamp" : ISODate("2016-01-14T14:47:13.597Z")
}
{
"_id" : ObjectId("5697528237b79c198c94ad1e"),
"actionName" : "touchMove",
"timeStamp" : ISODate("2016-01-14T16:01:49.620Z")
}
{
"_id" : ObjectId("5697528237b79c198c94ad1b"),
"actionName" : "touchDown",
"timeStamp" : ISODate("2016-01-14T16:01:50.010Z")
}
{
"_id" : ObjectId("5697528237b79c198c94ad17"),
"actionName" : "touchMove",
"timeStamp" : ISODate("2016-01-14T16:01:49.630Z")
}
And here is my query code
db.getCollection('app1_touchpoint').find({
'timeStamp' : {'$lte':new Date(2016, 01, 14, 15, 00)}
})
When I do query, the data that have a 'timeStamp' more than 2016-01-14 15:00 are shown in the result too. Actually all data are shown.
Is anyone able to give me some advice as to how I should do this query in the right way? Thank you.
The date you are adding to your query is a local date by default in c#. But - dates in mongo are utc by default.
You have a couple of options.
Move to a place that's on the other side of the utc line. This will solve your problem for lte, but may create a problem for gte.
Use DateTimeKind.Utc and set that date type to utc before you use it to query.
For Example
If I were going to do that with your sample data, I'd do it this way:
var dt = DateTime.SpecifyKind(new Date(2016, 01, 14, 15, 0, 0), DateTimeKind.Unspecified);
db.getCollection('app1_touchpoint').find({
'timeStamp' : {'$lte':dt}
});
I assume the goal is to query the dates in your db as they sit (not to query them AFTER you convert those dates to your timezone). This will accomplish that goal.

Unable to retrieve date field from mongodb

The date field when save to mongodb is in the format of:
{ "_id" : ObjectId("4f03283e1d4ee82215000002"), "name" : "nano3",
"category_id" : ObjectId("4f022b411d4ee8105700001c"), "price" : 20,
"production_date(3i)" : "1", "production_date(2i)" : "1",
"production_date(1i)" : "2011", "description" : "a music player with
video play function" }
when I try to get the date using #product.production_date from my model it failed. I am using Mongoid mapper
It fails because you don't have any fields named "production_date".
What you do have is fields named "production_date(3i)", "production_date(2i)", and "production_date(1i)".
You should be saving instances of the time class which can be properly serialized by the ruby driver.
Time.now or Time.utc(2011,1,1) will probably do what you want.

MongoDB + Node.js: unable to insert date properly

I′ve been using node-mongoskin to connect this two. Everything was ok until I queried some "date" field which I think should be returned as javascript′s Date object. But result′s type was string, which is odd (for me) and inconvenient.
Inserting looks something like this:
var doc = {
date: new Date(),
info: 'Some info'
}
db.users.insert( doc, {safe: true}, function(err, res) {
...
});
And result of above is (without _id field):
{ "date" : "Mon Oct 24 2011 18:00:57 GMT+0400 (MSK)", "info": "Some info" }
However, inserting with MongoDB Shell works just fine, except type of field is ISODate
> db.things.insert({ date: new Date() }); db.things.find();
{ "_id" : ObjectId("4eae9f2a34067b92db8deb40"), "date" : ISODate("2011-10-31T13:14:18.947Z") }
So, the question is: how should I insert documents to query date fields as Date object? What I want is setting fields on database-server-side. I just send something like null-fields, and db-server setting those for me using default mongo′s mechanisms.
Inserting timestamps (as native MongoDB timestamp) is also a problem, but it′s not such a big deal.
PS: No luck going through mongoskin and mongodb-native docs.
It was probably some bug in my code or the mongo driver. Now, the following works just fine:
db.collection.insert({d: new Date()});
Timestamps support described here: http://mongodb.github.com/node-mongodb-native/api-bson-generated/timestamp.html.
ISODate is the native way for mongo to store date. I use node-mongodb-native npm module and I store/retrieve javascript Date using new Date() idiom like in your examples. I don't know if it's a recent correction because I started node and Mongo in 2012, but using date was pretty straightforward for me.
JavaScript code:
collection.insert({"className" : "models.Action",
"title" : "Email",
"description" : "How are you today?",
"creationDate" : new Date("Fry, 4 May 2012 10:30:08 +0200 (CEST)"),
"creator" : dbref },
produced in mongoDB
db.action.find({"title":"Email"})
> db.action.find({"title":"Email"})
{ "className" : "models.Action", "title" : "Email", "description" : "How are you today?", "creationDate" : ISODate("2012-05-04T08:30:08Z"), "creator" : { "$ref" : "person", "$id" : ObjectId("4f995e4824ac8d68f63adf69") }, "_id" : ObjectId("4fa79e2e92c2a19a09000002") }