Good morning! I have mongodb base:
{
"_id" : ObjectId("........."),
"0" : {
"title" : "name",
"description" : "database"
},
"1" : {
"title" : "name2",
"description" : "database"
},
"2" : {
"title" : "name3",
"description" : "database"
},
"3" : {
"title" : "name4",
"description" : "database"
},
"4" : {
"title" : "name5",
"description" : "database"
},
...
How do I search by name with regex?
I've tried, but I'm probably search not inside the array, right?
db.test.find({"title": /.*n.*/})
CodePudding user response:
- change object to key-value aray
- filter the array with regex
- if array is not empty then the doc is what you need
you can check the result in the mongoplayground link below
db.collection.aggregate([
{
$match: {
$expr: {
$ne: [
{
$filter: {
input: {
$objectToArray: "$$ROOT"
},
as: "r",
cond: {
$regexMatch: {
input: "$$r.v.title",
regex: "name2"
}
}
}
},
[]
]
}
}
}
])