我的复杂结构类似于:
{
type: "Data",
data: [
"item1": {...},
"item2": {...},
...
"itemN": {
"otherStructure": {
"testData": [
{
"values": {...}
},
{
"values": {
"importantKey": ObjectId("23a2345gf651")
}
}
]
}
}
]
}
对于这种数据结构,我想将所有这些importantKeys
的数据类型从ObjectId更新为字符串。
我正在尝试类似的查询:
db.collection.updateMany(
{type:"Data"},
{$toString: "data.$[element].otherStructure.testData.$[element].values.importantKey"},
{"data.element.otherStructure.testData.element.values.importantKey": {$type: "objectId"}})
但是所有这些尝试都没有成功。
那么,是否有适当的解决方案来更新此类数据?
您可以使用此解决方法:
db.collection.aggregate([
{
$addFields: {
data: {
$map: {
input: "$data",
as: "data",
in: {
item: {
$map: {
input: "$$data.item.otherStructure.testData",
as: "testData",
in: {
"values": {
"importantKey": {
$toString: "$$testData.values.importantKey"
}
}
}
}
}
}
}
}
}
},
{
$out: "collection"
}
])