【发布时间】:2025-12-25 15:55:11
【问题描述】:
我遇到了一个问题,我需要根据在字段值中查找“x”字符的正则表达式删除数据库中的一些条目。这是我的数据结构:
{
"_id" : ObjectId("5e0effac04d45483d97cb4c3"),
"formId" : ObjectId("5d076f7db166bcae2743554a"),
"revisionNo" : 0,
"customerUserId" : ObjectId("5d0889fde55fbc38509e5825"),
"formElements" : [
{
"formElementId" : ObjectId("5d1a047cae7a711848238c26"),
"type" : "text",
"label" : "Intersection number",
"value" : null,
"dynamicTypeData" : {
"required" : false,
"value" : "TK47ax"
}
},
{
"formElementId" : ObjectId("5d1a058cae7a711848238c27"),
"type" : "select",
"label" : "Municipality",
"value" : null,
"dynamicTypeData" : {
"attributes" : null,
"options" : [
],
"required" : false
}
},
{
"formElementId" : ObjectId("5d00ec9a9001eb637c8466f4"),
"type" : "select",
"label" : "Signtype for setup",
"value" : null,
"dynamicTypeData" : {
"attributes" : null,
"options" : [
],
"required" : false
}
},
{
"formElementId" : ObjectId("5d00ee749001eb637c8466fc"),
"type" : "select",
"label" : "Sign size",
"value" : null,
"dynamicTypeData" : {
"attributes" : null,
"options" : [
],
"required" : false
}
},
{
"formElementId" : ObjectId("5d00eced9001eb637c8466f5"),
"type" : "select",
"label" : "Route number",
"value" : null,
"dynamicTypeData" : {
"attributes" : null,
"options" : [
],
"required" : false
}
},
{
"formElementId" : ObjectId("5d00eeba9001eb637c8466fe"),
"type" : "select",
"label" : "Stand",
"value" : null,
"dynamicTypeData" : {
"attributes" : null,
"options" : [
],
"required" : false
}
},
{
"formElementId" : ObjectId("5d00ee849001eb637c8466fd"),
"type" : "select",
"label" : "Foundation",
"value" : null,
"dynamicTypeData" : {
"attributes" : null,
"options" : [
],
"required" : false
}
},
{
"formElementId" : ObjectId("5d00ed0f9001eb637c8466f6"),
"type" : "textarea",
"label" : "Remarks regaring the new signs placement",
"value" : null,
"dynamicTypeData" : {
"value" : null,
"required" : false
}
}
]
}
所以我想要找到的是每个元素都与 label: "Intersection number" 匹配,其值在其 dynamicTypeData 对象中包含字符 x。我知道我可以在控制台中执行以下操作:db.getCollection('formRegistrations').find({formId: ObjectId("5d0889fde55fbc38509e5825")}) but how to get all the way down to thedynamicTypeData` 对象并与其中的值匹配,我不知道。请帮忙 :) 感谢阅读
编辑
虽然给定的答案是正确的,但我仍然只想找到具有这些参数的给定注册,因为我必须在删除之前手动查看数据,因为这是在生产服务器上完成的。因此,根据下面给出的答案,我制定了自己的脚本:
db.formRegistrations.find(
{
formId: ObjectId("5d076f7db166bcae2743554a"),
"formElements.0.label": "Intersection number",
"formElements.0.dynamicTypeData.value": {
$regex: /.*x/
}
}
)
希望这对我以外的人有所帮助
【问题讨论】:
-
从上面的链接看,对于多个文档::
db.getCollection('formRegistrations').updateMany( { 'formElements.label': "Intersection number"}, { $pull: { 'formElements': {'dynamicTypeData.value' : /x/}} } )或者对于一个特定的文档::db.getCollection('formRegistrations').update( { "_id" : ObjectId("5e0effac04d45483d97cb4c3"), 'formElements.label': "Intersection number"}, { $pull: { 'formElements': {'dynamicTypeData.value' : /x/}} } )
标签: mongodb