Search for string part in mongo by php?

0

How to:

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

Using PHP MongoDB \ BSON \ Regex?

    
asked by anonymous 04.05.2018 / 18:41

1 answer

0

There is 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 for all records that begin with X letter, number and or word, the caret character ( ^ ) is used before the term key:

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

search for 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 independent search of uppercase or lowercase, please report the flag:

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

To find that contains X letter, number and or word, just enter the term key:

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 search for all records that end with X letter, number and or word, the dollar sign ( $ ) character is used after the key term:

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

For more information, see this tutorial in the MongoDB documentation English .

    
15.05.2018 / 17:39