Cómo consultar MongoDB con "me gusta"?


Quiero consultar algo como la consulta de SQL like:

select * 
from users 
where name like '%m%'

¿Cómo hacer lo mismo en MongoDB?
No puedo encontrar un operador para likeen las documentaciones .

Author: shA.t, 2010-07-22

30 answers

Eso tendría que ser:

db.users.find({"name": /.*m.*/})

O, similar:

db.users.find({"name": /m/})

Está buscando algo que contenga "m" en algún lugar (el operador '%' de SQL es equivalente al '.*' de Regexp), no algo que tenga "m" anclado al principio de la cadena.

 1479
Author: Kyle H,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-14 04:07:37
db.users.insert({name: 'paulo'})
db.users.insert({name: 'patric'})
db.users.insert({name: 'pedro'})

db.users.find({name: /a/})  //like '%a%'

Fuera: paulo, patric

db.users.find({name: /^pa/}) //like 'pa%' 

Fuera: paulo, patric

db.users.find({name: /ro$/}) //like '%ro'

Fuera: pedro

 249
Author: Johnathan Douglas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-28 18:53:40

En

  • PyMongo usando Python
  • Mangostausando el nodo .js
  • Jongo , usando Java
  • mgo , usando Go

Puedes hacer:

db.users.find({'name': {'$regex': 'sometext'}})
 199
Author: Afshin Mehrabani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-27 13:17:41

En PHP, puedes usar el siguiente código:

$collection->find(array('name'=> array('$regex' => 'm'));
 76
Author: leon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-10 10:04:26

Usarías expresiones regulares para eso en mongo.

Ej: db.users.find({"name": /^m/})

 43
Author: Joshua Partogi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-07-22 03:48:56

Si se usa el nodo .js, dice que puedes escribir esto:

db.collection.find( { field: /acme.*corp/i } );
//or
db.collection.find( { field: { $regex: 'acme.*corp', $options: 'i' } } );

También, puedes escribir esto:

db.collection.find( { field: new RegExp('acme.*corp', 'i') } );
 26
Author: Eddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-21 07:44:03

Ya Hay muchas respuestas. Estoy dando diferentes tipos de requisitos y soluciones para la búsqueda de cadenas con expresiones regulares.

Se puede hacer con expresiones regulares que contienen la palabra es decir, como. También se puede utilizar $options => i para la búsqueda insensible a mayúsculas y minúsculas

Contiene string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})

No Contiene string solo con expresiones regulares

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})

Insensible a mayúsculas y minúsculas string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})

Comienza con string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})

Termina con string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})

Mantenga esto como un marcador, y una referencia para cualquier otra alteración que pueda necesitar.

 23
Author: Somnath Muluk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-11 15:39:09

Tienes 2 opciones:

db.users.find({"name": /string/})

O

db.users.find({"name": {"$regex": "string", "$options": "i"}})

En el segundo tienes más opciones, como "i" en opciones para encontrar usando mayúsculas y minúsculas. Y sobre la "cadena", puedes usar como ".cadena. " (%string%), o "string.* "(string%) and ".* string) (%string) por ejemplo. Puede usar expresiones regulares como desee.

Disfrute!

 15
Author: user3645907,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-25 21:58:19

Ya u obtuvo las respuestas, pero para que coincida con la expresión regular con la insensibilidad a mayúsculas y minúsculas

Puede utilizar la siguiente consulta

db.users.find ({ "name" : /m/i } ).pretty()

El i en el /m/i indica insensibilidad a mayúsculas y minúsculas y .pretty() proporciona una salida más bonita

 14
Author: The6thSense,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-23 11:21:39

Para Mangosta en Nodo.js

db.users.find({'name': {'$regex': '.*sometext.*'}})
 11
Author: Aqib Mumtaz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-10 11:39:29

Puede usar la nueva característica de 2.6 mongodb:

db.foo.insert({desc: "This is a string with text"});
db.foo.insert({desc:"This is a another string with Text"});
db.foo.ensureIndex({"desc":"text"});
db.foo.find({
    $text:{
        $search:"text"
    }
});
 10
Author: cmarrero01,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-04 19:19:03

Para PHP mongo Like.
Tuve varios problemas con php mongo como. descubrí que concatenar los parámetros regex ayuda en algunas situaciones El campo PHP mongo find comienza con . Pensé que publicaría aquí para contribuir al hilo más popular

E. g

db()->users->insert(['name' => 'john']);
db()->users->insert(['name' => 'joe']);
db()->users->insert(['name' => 'jason']);

// starts with
$like_var = 'jo';
$prefix = '/^';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);
output: (joe, john)

// contains
$like_var = 'j';
$prefix = '/';
$suffix = '/';
$name = $prefix . $like_var . $suffix;
db()->users->find(['name' => array('$regex'=>new MongoRegex($name))]);

output: (joe, john, jason)
 9
Author: Dap,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:18:14

In nodejs project and use mongoose use Like query

var User = mongoose.model('User');

var searchQuery={};
searchQuery.email = req.query.email;
searchQuery.name = {$regex: req.query.name, $options: 'i'};
User.find(searchQuery, function(error, user) {
                if(error || user === null) {
                    return res.status(500).send(error);
                }
                return res.status(200).send(user);
            });
 8
Author: Shaishab Roy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-10 18:57:51

Puede usar la instrucción where para construir cualquier script JS:

db.myCollection.find( { $where: "this.name.toLowerCase().indexOf('m') >= 0" } );

Referencia: http://docs.mongodb.org/manual/reference/operator/where/

 6
Author: Crasher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-05 14:53:27

En SQL, la consulta' like ' se ve así:

select * from users where name like '%m%'

En la consola MongoDB, se ve así:

db.users.find({"name": /m/})     // Not JSON formatted

db.users.find({"name": /m/}).pretty()  // JSON formatted

In addion pretty() método en todos los lugares donde producir estructura JSON formateada que es más legible.

 6
Author: MAA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-19 11:15:12

Utilice expresiones regulares que coincidan como se muestra a continuación. La' i ' muestra insensibilidad a las mayúsculas y minúsculas.

var collections = mongoDatabase.GetCollection("Abcd");

var queryA = Query.And(
         Query.Matches("strName", new BsonRegularExpression("ABCD", "i")), 
         Query.Matches("strVal", new BsonRegularExpression("4121", "i")));

var queryB = Query.Or(
       Query.Matches("strName", new BsonRegularExpression("ABCD","i")),
       Query.Matches("strVal", new BsonRegularExpression("33156", "i")));

var getA = collections.Find(queryA);
var getB = collections.Find(queryB);
 6
Author: Shalabh Raizada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-16 11:20:25

En Go y el controlador mgo:

Collection.Find(bson.M{"name": bson.RegEx{"m", ""}}).All(&result)

Donde result es la instancia de estructura del tipo buscado

 5
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-17 21:50:16

Como consulta sería como se muestra a continuación

db.movies.find({title: /.*Twelve Monkeys.*/}).sort({regularizedCorRelation : 1}).limit(10);

Para scala ReactiveMongo api,

val query = BSONDocument("title" -> BSONRegex(".*"+name+".*", "")) //like
val sortQ = BSONDocument("regularizedCorRelation" -> BSONInteger(1))
val cursor = collection.find(query).sort(sortQ).options(QueryOpts().batchSize(10)).cursor[BSONDocument]
 4
Author: prayagupd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-18 09:55:15

Con MongoDB Compass, necesita usar la sintaxis de modo estricto, como tal:

{ "text": { "$regex": "^Foo.*", "$options": "i" } }

(En MongoDB Compass, es importante que uses " en lugar de ')

 4
Author: damd,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-19 08:01:35

Si está utilizando Spring-Data Mongodb Puede hacer esto de esta manera:

String tagName = "m";
Query query = new Query();
query.limit(10);        
query.addCriteria(Criteria.where("tagName").regex(tagName));
 3
Author: Vaibhav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-28 10:34:23

Como el shell de Mongo soporta regex, eso es completamente posible.

db.users.findOne({"name" : /.*sometext.*/});

Si queremos que la consulta sea insensible a mayúsculas y minúsculas, podemos usar la opción "i", como se muestra a continuación:

db.users.findOne({"name" : /.*sometext.*/i});
 3
Author: sravanthi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-19 08:09:23

Si quieres' Me gusta ' buscar en mongo entonces usted debe ir con reg regex mediante el uso de esta consulta será

db.product.find({name:{$regex:/m/i}})

Para más información puede leer la documentación también. https://docs.mongodb.com/manual/reference/operator/query/regex /

 3
Author: jarry jafery,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-23 15:03:51

Parece que hay razones para usar tanto el patrón javascript /regex_pattern/ como el patrón mongo {'$regex': 'regex_pattern'}. Ver: Restricciones de sintaxis REGEX de MongoBD

Este no es un tutorial de expresiones REGULARES completo, pero me inspiré para ejecutar estas pruebas después de ver un altamente votado mensaje ambiguo por encima de.

> ['abbbb','bbabb','bbbba'].forEach(function(v){db.test_collection.insert({val: v})})

> db.test_collection.find({val: /a/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.*a.*/})
{ "val" : "abbbb" }
{ "val" : "bbabb" }
{ "val" : "bbbba" }

> db.test_collection.find({val: /.+a.+/})
{ "val" : "bbabb" }

> db.test_collection.find({val: /^a/})
{ "val" : "abbbb" }

> db.test_collection.find({val: /a$/})
{ "val" : "bbbba" }

> db.test_collection.find({val: {'$regex': 'a$'}})
{ "val" : "bbbba" }
 3
Author: Bruno Bronosky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:53

Encontré una herramienta gratuita para traducir consultas MYSQL a MongoDB. http://www.querymongo.com / Comprobé con varias consultas. como veo, casi todas son correctas. De acuerdo con eso, la respuesta es

db.users.find({
    "name": "%m%"
});
 2
Author: Lakmal Vithanage,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-06 05:07:03

Regex son costosos son proceso.

Otra forma es crear un índice de texto y luego buscarlo usando $search.

Cree un índice de texto de los campos que desea que se puedan buscar:

db.collection.createIndex({name: 'text', otherField: 'text'});

Buscar una cadena en el índice de texto:

db.collection.find({
  '$text'=>{'$search': "The string"}
})
 2
Author: user3284463,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-16 05:59:08

MongoRegex ha sido obsoleto.
Use MongoDB\BSON \ Regex

$regex = new MongoDB\BSON\Regex ( '^m');
$cursor = $collection->find(array('users' => $regex));
//iterate through the cursor
 1
Author: Albert s,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-27 20:06:51

Si estás usando PHP, puedes usar MongoDB_DataObject wrapper como abajo:

$model = new MongoDB_DataObject();

$model->query("select * from users where name like '%m%'");

while($model->fetch()) {
    var_dump($model);
}

O:

$model = new MongoDB_DataObject('users);

$model->whereAdd("name like '%m%'");

$model->find();

while($model->fetch()) {
    var_dump($model);
}
 1
Author: CEDA,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-16 08:34:08

FullName like 'last'with status = = 'Pending' between two dates:

db.orders.find({
      createdAt:{$gt:ISODate("2017-04-25T10:08:16.111Z"),
      $lt:ISODate("2017-05-05T10:08:16.111Z")},
      status:"Pending",
      fullName:/last/}).pretty();

Status = = 'Pending' y OrderID COMO 'PHA876174':

db.orders.find({
     status:"Pending",
     orderId:/PHA876174/
     }).pretty();
 1
Author: Shubham Verma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-06 08:38:57
db.customer.find({"customerid": {"$regex": "CU_00000*", "$options": "i"}}).pretty()

Cuando estamos buscando patrones de cadena, siempre es mejor usar el patrón anterior como cuando no estamos seguros sobre case. Espero que ayude!!!

 1
Author: priya raj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-02 06:06:13

Utilice la búsqueda de subcadenas de agregación (con índice!!!):

db.collection.aggregate([{
        $project : {
            fieldExists : {
                $indexOfBytes : ['$field', 'string']
            }
        }
    }, {
        $match : {
            fieldExists : {
                $gt : -1
            }
        }
    }, {
        $limit : 5
    }
]);
 1
Author: kz_sergey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-03 19:16:55