Search for part of string in php?

Asked

Viewed 436 times

0

How to do :

db.getCollection('Collection').find({“field”: /.*A.*/}) 

using PHP Mongodb BSON Regex?

1 answer

0


There’s no secret, let’s assume we have these records:

{ "_id" : ObjectId("5afae5b338597ce11fc99dc0"), "nome" : "Maria da Silva" }
{ "_id" : ObjectId("5afae5bd38597ce11fc99dc1"), "nome" : "Anderson de Souza" }
{ "_id" : ObjectId("5afae5d238597ce11fc99dc2"), "nome" : "Aline Santos Soares" }
{ "_id" : ObjectId("5afaf370af3f834caebe3c4a"), "nome" : "Thon de Souza" }
{ "_id" : ObjectId("5afaf510af3f834caebe3c4b"), "nome" : "amanda de lima 43" }
{ "_id" : ObjectId("5afaf687af3f834caebe3c4c"), "nome" : "4632 sem nome" }
{ "_id" : ObjectId("5afaf7c8af3f834caebe3c4d"), "nome" : "76 joana silveira" }

To search all records beginning with X letter, number and word, the circumflex character is used ( ^ ) before the key term:

new MongoDB\Driver\Query(['nome' => new MongoDB\BSON\Regex('^\d') ]);
> 4632 sem nome
> 76 joana silveira

retrieve all records beginning with X letter or word in uppercase:

new MongoDB\Driver\Query(['nome' => new MongoDB\BSON\Regex('^A') ]);
Anderson de Souza
Aline Santos Soares

for search regardless of being uppercase or lowercase, enter the flag:

new MongoDB\Driver\Query(['nome' => new MongoDB\BSON\Regex('^a', 'i') ]);
> Anderson de Souza
> Aline Santos Soares
> amanda de lima 43

To seek it out X letter, number and word, enter only the key term:

new MongoDB\Driver\Query(['nome' => new MongoDB\BSON\Regex('an') ]);
> Aline Santos Soares
> amanda de lima 43
> 76 joana silveira

new MongoDB\Driver\Query(['nome' => new MongoDB\BSON\Regex('\d') ]);
> amanda de lima 43
> 4632 sem nome
> 76 joana silveira

And finally, to get all the records that end with X letter, number and word, use the dollar character ( $ ) after the term key:

new MongoDB\Driver\Query(['nome' => new MongoDB\BSON\Regex('s$') ]);
> Aline Santos Soares

For more information, see this tutorial in the Mongodb documentation ( in English).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.