database - MongoDB:从 ObjectId 更新为许多文档的字符串
问题描述
我有一个复杂的结构,类似于:
{
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"}})
但所有这些尝试都没有成功。
那么,是否有任何适当的解决方案来更新此类数据?
更新 对不起,我的结构更复杂:
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"}
])
推荐阅读
- node.js - 在 Cloud Functions 中无法进行 Firebase 身份验证
- javascript - ASP.NET JQuery 无法访问服务器和 HTML 控件
- java - Anylogic新分支抛出“无法解析为变量”错误
- ffmpeg - 硬件加速 RPI4 FFmpeg
- python - FileNotFoundError: [Errno 2] 没有这样的文件或目录?
- javascript - 如何在没有明确输入区域的情况下使用快捷方式提交表单?
- angular - 使用事件发射我想将服务数据从组件 A 传递到 B
- python - 类型错误:切片索引必须是整数或无或在零填充 CAGAN 中具有 __index__ 方法
- python - 在 pyinstaller 之后无法导入名称“pywrap_tensorflow”
- javascript - 如何从对象的对象中删除重复项