MongoDB - 转换数组中每个对象的值
MongoDB - Convert values of each object in array
所以我有以下结构的文档:
username: "JohnDoe"
activities: [
{
name: "tennis",
lastTime: <number>
},
{
name: "soccer",
lastTime: <number>
}
]
我想在文档的每个 activity 对象中将“lastTime”字段从数字转换为日期。
我过去已经将数字转换为日期,但它是一个像这样的直接字段:
name: "Thomas",
birthday: <number>
我使用了这个查询:
db.coll.updateOne({name: "Thomas"},[{$set: {"birthday": {$toDate: "$birthday"}}}])
但是如果我现在尝试类似的东西,比如:
db.coll.updateOne({username: "JohnDoe"},[{$set: {"activities.lastTime": {$toDate: "$activities.lastTime"}}}])
它 returns“$convert 中不支持从数组到日期的转换,没有 onError 值”。
我有点明白了,但我不知道该怎么办...
好的,所以我继续挖掘,发现我需要使用 $map。
https://docs.mongodb.com/manual/reference/operator/aggregation/map/
这是它:
db.coll.updateOne(
{username: "JohnDoe"},
[{$set: {
"activities": {
$map: {
input: "$activities",
in: {
name: "$$this.name",
lastTime: {$toDate: "$$this.lastTime"},
}
}
}
}}]
)
编辑:
或者更好,如果我只想更改“lastTime”字段:
db.coll.updateOne(
{username: "JohnDoe"},
[{$set: {
"activities": {
$map: {
input: "$activities",
in: {
$mergeObjects: ["$$this",{lastTime: {$toDate: "$$this.lastTime"}}]
}
}
}
}}]
)
所以我有以下结构的文档:
username: "JohnDoe"
activities: [
{
name: "tennis",
lastTime: <number>
},
{
name: "soccer",
lastTime: <number>
}
]
我想在文档的每个 activity 对象中将“lastTime”字段从数字转换为日期。
我过去已经将数字转换为日期,但它是一个像这样的直接字段:
name: "Thomas",
birthday: <number>
我使用了这个查询:
db.coll.updateOne({name: "Thomas"},[{$set: {"birthday": {$toDate: "$birthday"}}}])
但是如果我现在尝试类似的东西,比如:
db.coll.updateOne({username: "JohnDoe"},[{$set: {"activities.lastTime": {$toDate: "$activities.lastTime"}}}])
它 returns“$convert 中不支持从数组到日期的转换,没有 onError 值”。 我有点明白了,但我不知道该怎么办...
好的,所以我继续挖掘,发现我需要使用 $map。 https://docs.mongodb.com/manual/reference/operator/aggregation/map/
这是它:
db.coll.updateOne(
{username: "JohnDoe"},
[{$set: {
"activities": {
$map: {
input: "$activities",
in: {
name: "$$this.name",
lastTime: {$toDate: "$$this.lastTime"},
}
}
}
}}]
)
编辑:
或者更好,如果我只想更改“lastTime”字段:
db.coll.updateOne(
{username: "JohnDoe"},
[{$set: {
"activities": {
$map: {
input: "$activities",
in: {
$mergeObjects: ["$$this",{lastTime: {$toDate: "$$this.lastTime"}}]
}
}
}
}}]
)