How to store TimeStamp? Is there automatic field for CreatedOn - mongodb

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();

Related

Fetching Data from MongoDB according createdAt column only with date

I have collection Ticket_master,which like as follows
Ticket_master
{
_id:5e70ed53de0f7507d4da8dc2,
"TICKET_NO" : 1000,
"SUBJECT" : "Sub1",
"DESCRIPTION" : "Desc1",
"createdAt" : ISODate("2020-03-17T15:31:31.039Z"),
}
Already tried with the following code snippet and it returns null result set.
db.getCollection('ticket_masters').find({ 'createdAt':ISODate('2020-03-17T00:00:00.000Z')})
How fetch fetch data from ticket_master collection by matching the value with date of creation column,which is represented as createdAt.
Following code snippets return the results. Because it contain both date and time.How fetch data from the collection only with Date .
db.getCollection('ticket_masters').find({ 'createdAt':ISODate('2020-03-17T15:31:31.039+00:00')})
as long as you are searching for all the tickets that have been created on some day, so you can use a date range to filter the tickets
db.getCollection('ticket_masters').find({
createdAt : {
$gte: ISODate('2020-03-17T00:00:00.000Z'),
$lt: ISODate('2020-03-18T00:00:00.000Z')
}
})
this should return all the tickets that have been created on 17/03/2020
check this Mongo Playground

Mongo Upsert $in values from Find That were Not found

I have to run mongo updates for employee id linked to a supervisorId (That's an oversimplification, but its the gist of what I need). The find uses a list of employee ids, and if the employee id is not found, I have an upsert to add the data. However the issue is I'm not getting the employee id in the upsert. Is it possible to upsert values from the $in array?
Eg:
db.collection.update({
empId:{
$in:['EMP1','EMP2','EMP3']
}
},
{$set: {SupervisorId:'SUP25'}},
{upsert:true},
{multi:true})
If I run this query I get one new doc with _id and SupervisorId:
{
"_id" : ObjectId("5e56ece8b0ae3537d0261ghg"),
"SupervisorId" : "SUP25"
}
I would like to get this in my upserts:
{
"_id" : ObjectId("5e56ece8b0ae3537d0261ghg"),
"SupervisorId" : "SUP25"
"EmpId": "EMP1"
}
I'm still getting comfortable with mongo, but is this even possible with an upsert? If not possible, are there any options for something similar?
MongoDB version 2.9.1

Join 2 Mongo DB tables with Id and ObjectId

My Scenario : I need to join 2 below tables in Mongo DB and condition is
testScenarioId(table 1) = _id (table 2)
Table 1:
{
"_id" : ObjectId("58516a6838fdb54d744ba070"),
"_class" : "com.TestResults",
"testScenarioId" : "581cef861892ad1eb7d124dd",
"runId" : 314,
"status" : "passed"
}
Table 2:
{
"_id" : ObjectId("57f41cb9319ed34079df8a2d"),
"environment" : "STAGE",
"component" : "platform",
"scenarioName" : "ABC-1234",
}
i am able to do if i am joining with same local field and foreign field but not on the above case.
Mongodb does not support type coercion in $lookup. So field of type ObjectId can not be looked up with a string type foreign field.
What you need to do is while saving the testScenarioId, you need to store as objectId.
I tried using $type in aggregation but its not supported. So currently here is no way to do it directly in aggregation pipeline.
If you want to implement join in 2 collections, then you will be insert "testScenarioId" in ObjectId form.
At that time,you have insert id in string form and "lookup" Aggregation does not support this form of Id.
Reason why ObjectId: when query finds Id from first table (table 1), they will get id in ObjectId form, and after then they will compare id with second table parameter "testScenarioId" which was store in string form, and they will not match and query return null data.

MongoDB: If document exists VS If document does not exist

I'm a beginner at MongoDB and I'm currently pairing it with php to try to make the following work:
I want to create a database to store information that can get updated at any time but it needs to keep a "document added on:" date.
In sum:
IF document exists:
-Update everything in the document except the "document added on" date entry.
ELSE
-Create a document with the data + a "document added on: XXXXX" date.
In a case of a database with this format:
Database{ document{ User_ID: "12345", Name: "Joe", More_Info: "" Date_Added_To_DB: "1372291496", Last_Updated:"1372291556"}}
I've researched and asked around and the best I've got so far is a function that will update a whole document if it exists and create a new document if it does not.
db.Database.update({'User_ID' : $userID},{$set: {'fieldName' : new "data" }}, {upsert: true})
The question is how you determine that "the document" exists? Usually, you'd do this using a unique id. Now MongoDB's ObjectId comes to the rescue because it contains a timestamp already. This can also be used in queries.
Instead of using an integer field User_ID, you might want to consider calling the field _id and use the ObjectId data type so you get that functionality for free.
> db.test.insert({"foo" : "test"});
{ "_id" : ObjectId("51cb763e58bb4077aea65b3d"), "foo" : "test" }
> var foo = db.test.findOne();
> foo._id.getTimestamp();
ISODate("2013-06-26T23:16:14Z")

Why do I have to delete _id field in Mongo before updating?

My update that find a document, changes some fields and updates:
newdocument = db.collection.findOne{"id_" : ObjectId("2bfc42346cb2f36c4f3fc6264c")}
newdocument.somefield = "New value"
db.collection.update({"_id" : ObjectId("2bfc42346cb2f36c4f3fc6264c")}, newdocument)
does nothing unless, I remove the _id field from newdocument, i.e. del newdocument["_id"]. Is this the expected behaviour?
The id is immutable but the structure you wrote also not needed to use. Simply:
db.collection.update({"_id" : ObjectId("2bfc42346cb2f36c4f3fc6264c")}, {$set:{"somefield":"New value"}})
will work