Database MongoDB:对于许多文档,从ObjectId更新为string
我有一个复杂的结构,类似于:Database MongoDB:对于许多文档,从ObjectId更新为string,database,mongodb,mongodb-query,aggregation-framework,mongoid,Database,Mongodb,Mongodb Query,Aggregation Framework,Mongoid,我有一个复杂的结构,类似于: { type: "Data", data: [ "item1": {...}, "item2": {...}, ... "itemN": { "otherStructure": { "testData": [ { "values": {...}
{
type: "Data",
data: [
"item1": {...},
"item2": {...},
...
"itemN": {
"otherStructure": {
"testData": [
{
"values": {...}
},
{
"values": {
"importantKey": ObjectId("23a2345gf651")
}
}
]
}
}
]
}
db.collection.updateMany(
{type:"Data"},
{$toString: "data.$[element].otherStructure.testData.$[element].values.importantKey"},
{"data.element.otherStructure.testData.element.values.importantKey": {$type: "objectId"}})
对于这种数据结构,我想将所有这些重要键的数据类型从ObjectId更新为string
我尝试了以下类似的查询:
{
type: "Data",
data: [
"item1": {...},
"item2": {...},
...
"itemN": {
"otherStructure": {
"testData": [
{
"values": {...}
},
{
"values": {
"importantKey": ObjectId("23a2345gf651")
}
}
]
}
}
]
}
db.collection.updateMany(
{type:"Data"},
{$toString: "data.$[element].otherStructure.testData.$[element].values.importantKey"},
{"data.element.otherStructure.testData.element.values.importantKey": {$type: "objectId"}})
但所有这些尝试都没有成功
那么,是否有足够的解决方案来更新这些数据
更新
很抱歉搞混了,我的结构更复杂:
data.content.$[element].otherStructure.testData.keys.$[element].values.$[element].meta.importantKey
所有这些$[element]
元素意味着具有元素列表的对象。您可以使用以下解决方法:
db.collection.aggregate([
{
$addFields: {
"data.content": {
$map: {
input: "$data.content",
as: "data",
in: {
otherStructure: {
testData: {
keys: {
$map: {
input: "$$data.otherStructure.testData.keys",
as: "testData",
in: {
"values": {
$map: {
input: "$$testData.values",
as: "values",
in: {
"meta": {
"importantObject": {
"importantKey": {
$toString: "$$values.meta.importantObject.importantKey"
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
},
{$out:"collection"}
])
但如果某些具有类似结构的文档没有此属性,它将插入此属性,而只是更新现有属性的数据类型?@pythonista No,$map
将停止执行,如果没有任何具有预期结构的嵌套数组。您试图强制错误的结构,并检查它是否正确更新第二个元素在此处的处理方式?我有一个稍微复杂一点的结构,并试图理解这里的所有细节。(更新了原始帖子中的结构)@pythonista在这里共享您的示例数据我更新了您的配置部分。