0

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.*/})

1 Answer 1

0
  1. change object to key-value aray
  2. filter the array with regex
  3. 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"
                }
              }
            }
          },
          []
        ]
      }
    }
  }
])

mongoplayground

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, YuTing! 1) There are no other options? 2) I use php, is this the only option? And maybe tell me how to do it in php?
1. I cannot come with other options. 2. convert to php on your own
I accepted you answer. Can you please tell me, to use mongodb for 50 million records and search them with .*, is it a good idea or better not to do that? Or is it bad for nosql?
@Alex It depends on how long is your query take. If it takes minutes then it's a bad idea. If it takes seconds then it's maybe acceptable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.