MongoDB Operadores de condición

En este capítulo, discutiremos cómo usar operadores de condición en MongoDB.

En MongoDB, los operadores de condición se utilizan para filtrar, comparar y realizar operaciones lógicas al consultar documentos.

Estos operadores se pueden clasificar en las siguientes categorías: operadores de comparación, operadores lógicos, operadores de elementos, operadores de arrays y otros operadores comunes.

Operadores de comparación

Los operadores de comparación son:

OperadorDescripciónEjemplo
$eqIgual a{ age: { $eq: 25 } }
$neNo igual a{ age: { $ne: 25 } }
$gtMayor que{ age: { $gt: 25 } }
$gteMayor o igual que{ age: { $gte: 25 } }
$ltMenor que{ age: { $lt: 25 } }
$lteMenor o igual que{ age: { $lte: 25 } }
$inEn el array especificado{ age: { $in: [25, 30, 35] } }
$ninNo en el array especificado{ age: { $nin: [25, 30, 35] } }

$eq (igual a)

Sintaxis:

{ field: { $eq: value } }

Buscar personas con edad igual a 25:

db.collection.find({ age: { $eq: 25 } })

$ne (no igual a)

Sintaxis:

{ field: { $ne: value } }

Buscar personas con edad no igual a 25:

db.collection.find({ age: { $ne: 25 } })

$gt (mayor que)

Sintaxis:

{ field: { $gt: value } }

Buscar personas con edad mayor que 25:

db.collection.find({ age: { $gt: 25 } })

$gte (mayor o igual que)

Sintaxis:

{ field: { $gte: value } }

Buscar personas con edad mayor o igual a 25:

db.collection.find({ age: { $gte: 25 } })

$lt (menor que)

Sintaxis: { field: { $lt: value } }

Buscar personas con edad menor que 25:

db.collection.find({ age: { $lt: 25 } })

$lte (menor o igual que)

Sintaxis:

{ field: { $lte: value } }

Buscar personas con edad menor o igual a 25:

db.collection.find({ age: { $lte: 25 } })

$in (valor en el array)

Sintaxis:

{ field: { $in: [value1, value2, ...] } }

Buscar personas con edad entre 20, 25 y 30:

db.collection.find({ age: { $in: [20, 25, 30] } })

$nin (valor no en el array)

Sintaxis:

{ field: { $nin: [value1, value2, ...] } }

Buscar personas con edad que no esté entre 20, 25 y 30:

db.collection.find({ age: { $nin: [20, 25, 30] } })

Operadores lógicos

Los operadores lógicos son:

OperadorDescripciónEjemplo
$andAND lógico, cumple todas las condiciones{ $and: [ { age: { $gt: 25 } }, { city: "New York" } ] }
$orOR lógico, cumple cualquier condición{ $or: [ { age: { $lt: 25 } }, { city: "New York" } ] }
$notNegación, no cumple la condición{ age: { $not: { $gt: 25 } } }
$norNOR lógico, ninguna cumple{ $nor: [ { age: { $gt: 25 } }, { city: "New York" } ] }

$and (todas las condiciones se cumplen)

Sintaxis:

{ $and: [ { condition1 }, { condition2 } ] }

Buscar personas con edad mayor que 25 y menor que 35:

db.collection.find({ $and: [{ age: { $gt: 25 } }, { age: { $lt: 35 } }] })

$or (al menos una condición se cumple)

Sintaxis:

{ $or: [ { condition1 }, { condition2 } ] }

Buscar personas con edad mayor que 25 o menor que 18:

db.collection.find({ $or: [{ age: { $gt: 25 } }, { age: { $lt: 18 } }] })

$not (condición invertida)

Sintaxis:

{ field: { $not: { condition } } }

Buscar personas con edad no mayor que 25:

db.collection.find({ age: { $not: { $gt: 25 } } })

$nor (ninguna condición se cumple)

Sintaxis:

{ $nor: [ { condition1 }, { condition2 } ] }

Buscar personas con edad no mayor que 25 y no menor que 18:

db.collection.find({ $nor: [{ age: { $gt: 25 } }, { age: { $lt: 18 } }] })

Operadores de elementos

Los operadores de elementos son:

OperadorDescripciónEjemplo
$existsSi el campo existe{ age: { $exists: true } }
$typeTipo BSON del campo{ age: { $type: "int" } }

$exists (si el campo existe)

Sintaxis:

{ field: { $exists: boolean } }

Buscar documentos que contengan el campo age:

db.collection.find({ age: { $exists: true } })

$type (tipo de campo)

Sintaxis:

{ field: { $type: "type" } }

Buscar documentos donde el campo age sea de tipo entero:

db.collection.find({ age: { $type: "int" } })

Operadores de arrays

Los operadores de arrays son:

OperadorDescripciónEjemplo
$allEl array contiene todos los elementos especificados{ tags: { $all: ["red", "blue"] } }
$elemMatchLos elementos del array coinciden con la condición especificada{ results: { $elemMatch: { score: { $gt: 80, $lt: 85 } } } }
$sizeLa longitud del array es igual al valor especificado{ tags: { $size: 3 } }

Buscar documentos donde el array tags contenga "red" y "blue":

db.myCollection.find({ tags: { $all: ["red", "blue"] } });

$all (el array contiene todos los elementos especificados)

Sintaxis:

{ field: { $all: [value1, value2, ...] } }

Buscar documentos donde el array tags contenga "mongodb" y "database":

db.collection.find({ tags: { $all: ["mongodb", "database"] } })

$elemMatch (al menos un elemento del array cumple la condición)

Sintaxis:
{ field: { $elemMatch: { condition } } }

Buscar elementos en el array items donde quantity sea mayor que 10:

db.collection.find({ items: { $elemMatch: { quantity: { $gt: 10 } } } })

$size (tamaño del array)

Sintaxis:

{ field: { $size: value } }

Buscar documentos donde el array tags tenga tamaño 3:

db.collection.find({ tags: { $size: 3 } })

Otros operadores

Hay otros operadores como los siguientes:

OperadorDescripciónEjemplo
$regexCoincidir con expresión regular{ name: { $regex: /^A/ } }
$textRealizar búsqueda de texto{ $text: { $search: "coffee" } }
$whereFiltrar condiciones usando expresiones JavaScript{ $where: "this.age > 25" }
$nearBuscar documentos cercanos a un punto especificadodb.collection.find({ location: { $near: [10, 20], $maxDistance: 1000 } })
$geoWithinBuscar documentos dentro de un área geográfica especificadadb.collection.find({ location: { $geoWithin: { $centerSphere: [[10, 20], 1] } } })

$regex (coincidencia con expresión regular)

Sintaxis:

{ field: { $regex: "pattern" } }

Buscar documentos donde name comience con "John":

db.collection.find({ name: { $regex: /^John/ } })

$near (documentos cercanos a un punto especificado)

Sintaxis:

{ field: { $near: [longitude, latitude], $maxDistance: distance } }

Buscar documentos cercanos a una ubicación:

db.collection.find({ location: { $near: [10, 20], $maxDistance: 1000 } })

$geoWithin (buscar documentos dentro de un área especificada)

Sintaxis:

{ field: { $geoWithin: { $centerSphere: [[longitude, latitude], radius] } } }

Buscar documentos dentro de un área geográfica especificada:

db.collection.find({ location: { $geoWithin: { $centerSphere: [[10, 20], 1] } } })
Otras extensiones