如何更新文档(Mongo)中数组中的字段名称?
How to update field name in array in document(Mongo)?
在MongoDB
我收集了用户。我有这样的文件:
{
_id: ObjectId("619365c54a7d53716438933e"),
name: 'Chris',
hobbies: [
{ title: 'Sports', frequency: 5 },
{ title: 'Cooking', fequency: 5 },
{ title: 'Hiking', frequency: 1 }
],
isSporty: true,
cookMaster: true,
age: 35 }
所以,它有关于爱好的数组值,在插入期间我犯了一个错误。当我插入 hobby Cooking 时,我添加了 key fequeny 而不是 frequency。现在我想解决这个问题。在 Mong 中存在 $rename
这样的运算符。我试过:
db.users.updateMany({name:"Chris"}, {$rename: {"hobbies.fequency": "frequency"}})
但是得到了错误。我怎样才能正确丰富和更改此密钥?
只需使用 $set
进行更新以更正字段名称 $map
。
db.collection.update({},
[
{
"$set": {
"hobbies": {
"$map": {
"input": "$hobbies",
"as": "h",
"in": {
title: "$$h.title",
frequency: {
"$ifNull": [
"$$h.frequency",
"$$h.fequency"
]
}
}
}
}
}
}
])
这里是Mongo playground供大家参考。
$set
- $map
hobbies
数组字段,用 $mergeObject
添加新字段 frequency
.
$unset
- 删除 hobbies
数组字段中 fequency
的字段。
db.collection.update({
name: "Chris"
},
[
{
$set: {
"hobbies": {
$map: {
input: "$hobbies",
in: {
$mergeObjects: [
"$$this",
{
frequency: "$$this.fequency"
}
]
}
}
}
}
},
{
$unset: "hobbies.fequency"
}
])
在MongoDB
我收集了用户。我有这样的文件:
{
_id: ObjectId("619365c54a7d53716438933e"),
name: 'Chris',
hobbies: [
{ title: 'Sports', frequency: 5 },
{ title: 'Cooking', fequency: 5 },
{ title: 'Hiking', frequency: 1 }
],
isSporty: true,
cookMaster: true,
age: 35 }
所以,它有关于爱好的数组值,在插入期间我犯了一个错误。当我插入 hobby Cooking 时,我添加了 key fequeny 而不是 frequency。现在我想解决这个问题。在 Mong 中存在 $rename
这样的运算符。我试过:
db.users.updateMany({name:"Chris"}, {$rename: {"hobbies.fequency": "frequency"}})
但是得到了错误。我怎样才能正确丰富和更改此密钥?
只需使用 $set
进行更新以更正字段名称 $map
。
db.collection.update({},
[
{
"$set": {
"hobbies": {
"$map": {
"input": "$hobbies",
"as": "h",
"in": {
title: "$$h.title",
frequency: {
"$ifNull": [
"$$h.frequency",
"$$h.fequency"
]
}
}
}
}
}
}
])
这里是Mongo playground供大家参考。
$set
-$map
hobbies
数组字段,用$mergeObject
添加新字段frequency
.$unset
- 删除hobbies
数组字段中fequency
的字段。
db.collection.update({
name: "Chris"
},
[
{
$set: {
"hobbies": {
$map: {
input: "$hobbies",
in: {
$mergeObjects: [
"$$this",
{
frequency: "$$this.fequency"
}
]
}
}
}
}
},
{
$unset: "hobbies.fequency"
}
])