Javascript 将$currentDate字段插入Meteor中的MongoDB集合
不确定在Meteor中将文档插入MongoDB集合时如何使用 这只能用于更新,不能用于插入?这似乎很奇怪,但我看不到其他选择(除了使用Javascript 将$currentDate字段插入Meteor中的MongoDB集合,javascript,mongodb,meteor,mongodb-query,Javascript,Mongodb,Meteor,Mongodb Query,不确定在Meteor中将文档插入MongoDB集合时如何使用 这只能用于更新,不能用于插入?这似乎很奇怪,但我看不到其他选择(除了使用新日期) 示例 Stuff.insert({ owner: Meteor.userId(), createdAt: ..., // how to create this field with $currentDate ? theStuff: "Some of the good stuff" }) 笔记/想法/TL,DR 字段不能以$oper
新日期
)
示例
Stuff.insert({
owner: Meteor.userId(),
createdAt: ..., // how to create this field with $currentDate ?
theStuff: "Some of the good stuff"
})
笔记/想法/TL,DR
- 字段不能以$operators开头,或者据我所知,不能以大括号
开头{}
- 如果情况确实如此,那么让一个只处理更新的操作符有什么意义呢
- 为什么/何时
优于$currentDate
李>新日期
- 如果使用Moment.js esp,一件好事是$currentDate是以ISO 8601格式输入的
- 答案是从一开始就进行某种升级吗?如果是这样的话,这会产生意料之外的后果吗
集合.insert
方法一起使用。但是当istrue
时,当没有文档与查询条件匹配时,它将创建一个新文档。MongoDB运营商倾向于遵循
做一件事,把它做好
因此,每个操作员只应执行一项任务
为什么/何时$currentDate
优于新日期
首先,我想提到newdate
是一个JavaScriptDate实例
当您想将字段的值更新为当前日期时,可以使用$currentDate
和new Date
,但使用new Date
时,需要使用另一个字段才能工作。例如:
- 使用
新日期
db.collection.update({ "name": "bar" }, { "$set": { "date": new Date() }})
db.collection.update({ "name": "bar"}, { "$currentDate": { "date": { "$type": date }}} )
- 使用
$currentDate
db.collection.update({ "name": "bar" }, { "$set": { "date": new Date() }})
db.collection.update({ "name": "bar"}, { "$currentDate": { "date": { "$type": date }}} )
与
$currentDate
不同,它可以与insert
方法一起使用,如果Date
调用的参数大于on,则可以将值设置为特定值 您可以从插入操作中创建的自动生成的“\u id”中检索时间戳
只需使用以下方法:ObjectId.getTimestamp()
时间戳粒度以秒为单位 如果在集合模型中使用autoValue,它将变得更加简单
createdAt:
type: Date
autoValue: ->
if this.isInsert
return new Date
else if this.isUpsert
return $setOnInsert: new Date
else
this.unset()
在向其中插入或更新数据时,它将自动设置日期$currentDate用于$update构造时,可用于插入文档中不存在的字段 Mongodb 3.4的报价文件: 行为
If the field does not exist, $currentDate adds the field to a document.
还是。如果您有一个分布式应用程序连接到您的replicaSet/sharded群集,每秒插入大量文档,您希望createdAt字段保持一致,在插入上使用$currentDate将是一个更好的解决方案。如果插入量不高,upsert和insert对您来说可能是相同的,但实际上并非如此。Upsert速度较慢,并且当您使用新日期时,您是从客户机而不是从数据库服务器获取日期,因此在按createdAt排序时,很容易出现不一致的情况。@MestreSan
$currentDate
仅适用于updateOne
或updateMany
。不使用插入
。也许你在评论中说的“插入”是指“更新”。不@user3100115,我知道$currentDate
只适用于更新,不适用于插入。我的意思是,在insert中提供$currentDate
操作符是一个很好的特性。就像任何RDM在INSERT上都有now
功能一样,例如,可以在字段createdAt上使用该功能,以了解创建记录的准确时间。@MestreSan检查我对这个问题的回答,这可能是您所说的问题的一个解决方案:是否可以将$currentDate与$setOnInsert运算符结合使用。这将允许upsert\insert设置“创建”日期,而不会每次upsert\update都覆盖该日期。