Not sure how to use $currentDate when inserting a document into a MongoDB collection in Meteor.
Can this only be used in an update, not an insert? Would seem strange, but I don't see an alternative (other than using new Date instead).
Example
Stuff.insert({ owner: Meteor.userId(), createdAt: ..., // how to create this field with $currentDate ? theStuff: "Some of the good stuff" }) Notes / Thoughts / TL,DR
{}.$currentDate better than new Date? To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .
insertMany() method. insertMany() is a mongo shell method, which can insert multiple documents. This method can be used in the multi-document transactions. In this method, you can add documents in the collection with or without _id field.
To add a new field in the document after an existing field, hover over the row number in the dialog and click on the plus sign. The row number is not part of the document but is part of the dialog display.
Here mycol is our collection name, as created in the previous chapter. If the collection doesn't exist in the database, then MongoDB will create this collection and then insert a document into it. In the inserted document, if we don't specify the _id parameter, then MongoDB assigns a unique ObjectId for this document.
What's the point of having an operator that only works with updates, if that's indeed the case?
$currentDate is an update operator thus you can't use it with the collection.insert method. But when upsert is true it will create a new document when no document matches the query criteria. MongoDB operators tend to follow the Unix philosophy
Do One Thing and Do It Well
So each operator should perform only one task.
Why/when is
$currentDatebetter thannew Date?
First I would like to mention that new Date is a JavaScript Date instance.
$currentDate and new Date can be used when you want to update the value of a field to current date but with new Date you need to use another update operator for it to work. For example:
Using new Date
db.collection.update({ "name": "bar" }, { "$set": { "date": new Date() }}) Using $currentDate
db.collection.update({ "name": "bar"}, { "$currentDate": { "date": { "$type": date }}} ) Unlike $currentDate, new Date can be use with the insert method and value can be set to a particular if Date is call with more than on argument.
You can retrieve timestamp from autogenerated "_id" that is created within insert operation.
http://api.mongodb.com/java/current/org/bson/types/ObjectId.html
Just use the method : ObjectId.getTimestamp().
Timestamp granularity is in seconds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With