1

I'm just getting started with mongoDB, and coming from a MySQL environment I'm having trouble figuring out how have my documents automatically have fields such as UPDATED, CREATED, DELETED

So when I create an entry like this:

{
  "email": "some@test.com",
  "name": "bob"
}

I would like it to automatically become this:

{
  "email": "some@test.com",
  "name": "bob",
  "CREATED": 1567120458,
  "UPDATED": 1567120458,
  "DELETED": null
}

I have found https://docs.mongodb.com/manual/reference/operator/update/currentDate/ this resource which talks about a way of inserting dates, but I am not sure how to use this, or where to place this.

{ $currentDate: { <field1>: <typeSpecification1>, ... } }

I don't know what this piece of code means or where to use it.

I've installed Stuido 3T to help me manage the database, but I don't see any option to use this piece of code.

Amir
  • 4,211
  • 4
  • 23
  • 41

1 Answers1

1

Construct your query use Date:

db.example.insert({"date":new Date(Date.now())})
Dexter
  • 831
  • 8
  • 17
  • Just add the date fields to your insert query and mongodb will insert the current datetime value to it – Dexter Aug 30 '19 at 09:21
  • Your insert query should be: db.example.insert( { "email": "some@test.com", "name": "bob", "CREATED": new Date(Date.now()), "UPDATED": new Date(Date.now()), "DELETED": null }) – Dexter Aug 30 '19 at 09:23
  • so it means there is no automatic way to do this, on the database level? Because in MySQL, these dates are automatically populated by MySQL, there is no reason to do it manually every time. This feature does not exist for mongoDB? – Amir Aug 30 '19 at 13:15
  • Mongo is dynamic schema which is different. You’ve to explicitly pass the key and value if you need to store it in your db – Dexter Aug 30 '19 at 14:47