我正在尝试向集合中的所有文档添加一个新字段。
新字段应该是doc.name + "_" + doc.created
形式的concat
我写了以下代码-
db.test.find({}).forEach(function(doc) {
doc.externalId= doc.name + "_" + { "$dateToString": { "format": "%Y-%m-%d %H-%M", "date": doc.created } }
db.test.save(doc);
})
结果是
{
"_id" : ObjectId("621b63bec07bb9761216d08a"),
"name" : "test1",
"created" : ISODate("2021-07-12T08:22:16.688+0000"),
"externalId" : "test1_[object Object]"
}
{
"_id" : ObjectId("621b63bec07bb9761216d08b"),
"name" : "test2",
"created" : ISODate("2021-08-12T08:22:16.688+0000"),
"externalId" : "test2_[object Object]"
}
{
"_id" : ObjectId("621b63bec07bb9761216d08c"),
"name" : "test3",
"created" : ISODate("2021-09-12T08:22:16.688+0000"),
"externalId" : "test3_[object Object]"
}
我试着简单地连接现有的创建日期,但我无法控制返回日期的格式-
db.test.find({}).forEach(function(doc) {
doc.externalId= doc.name + "_" + doc.created;
db.test.save(doc);
})
输出-
{
"_id" : ObjectId("621b6413c07bb9761216d08d"),
"name" : "test1",
"created" : ISODate("2021-07-12T08:22:16.688+0000"),
"externalId" : "test1_Mon Jul 12 2021 11:22:16 GMT+0300 (Jerusalem Daylight Time)"
}
{
"_id" : ObjectId("621b6413c07bb9761216d08e"),
"name" : "test2",
"created" : ISODate("2021-08-12T08:22:16.688+0000"),
"externalId" : "test2_Thu Aug 12 2021 11:22:16 GMT+0300 (Jerusalem Daylight Time)"
}
{
"_id" : ObjectId("621b6413c07bb9761216d08f"),
"name" : "test3",
"created" : ISODate("2021-09-12T08:22:16.688+0000"),
"externalId" : "test3_Sun Sep 12 2021 11:22:16 GMT+0300 (Jerusalem Daylight Time)"
}
如何获取此对象的字符串值?我希望它返回类似ISODate-2021-07-12T08:22:16.688
的内容,甚至是它当前返回的内容,而不带GTM时间-Sun Sep 12 2021 11:22:16
(不带GMT+0300 (Jerusalem Daylight Time)
后缀(
感谢
编辑:
Mongo 3.4.19版
将externalId
逻辑移动为投影。
db.test.find({},
{
name: 1,
created: 1,
externalId: {
$concat: [
"$name",
"_",
{
"$dateToString": {
"format": "%Y-%m-%dT%H:%M:%S.%L",
"date": "$created"
}
}
]
}
})
.forEach(...)
Mongo游乐场示例
另一种方法是使用toISOString
方法;
db.test.find({}).forEach(function(doc) {
let created = doc.created.toISOString().split('Z')[0];
doc.externalId= doc.name + "_" + created;
db.test.save(doc);
})