Home > front end >  PHP Mongo Find in array
PHP Mongo Find in array

Time:04-12

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:

  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

  • Related