You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

1 Días
13 Hrs
5 Min
30 Seg

Usando $gt, $gte, $lt, $lte

19/30
Resources

What are comparison operators in MongoDB?

MongoDB, a NoSQL database, offers a wide variety of comparison operators that allow you to perform complex and precise queries on your data. These operators, similar to those we are familiar with in many programming languages, help you evaluate and filter documents within a collection. When working with numbers, operators such as greater than(>$gt), greater than or equal to($gte), less than($lt), and less than or equal to($lte), are essential for obtaining valuable information. With these operators, you can build more sophisticated and dynamic queries, especially when you are manipulating large volumes of data.

How to use comparison operators in MongoDB?

To use these operators, we must first set up a suitable working environment where we can manipulate our database and perform the necessary queries. Make sure you have access to your dataset and that you have properly configured your MongoDB project. Once this is done, we can start implementing the comparison operators in our queries.

Setting up the environment

  1. Create the project structure:

    • Create a new folder called Operators.
    • Copy the dataset you used in previous classes to ensure you work with the same information.
  2. Prepare the working file:

    • Create a file called Operators.mongodb.
    • Make sure you have your documents ready in the dataset to start working.

Using GreaterThan and GreaterThanOrEqual

To implement queries with the GreaterThan($gt) and GreaterThanOrEqual($gte) operators, follow these steps:

db.collection.find({ "field": { $gt: value }})
 db.collection.find({ "field": { $gte: value }})
  • $gt is used to find documents where the value of a field is greater than the specified value.
  • $gte searches for documents where the value is greater than or equal to the specified value.

Query example

Suppose we have a collection of students and we want to find those whose grade is greater than 85:

db.students.find({ " grade": { $gt: 85 } })

In this example, all documents in the students collection where the grade is greater than 85 will be returned.

What other comparison operators can we use?

MongoDB offers a full range of operators, not limited only to the ones mentioned above. The comparison operators are part of a robust set that allows you to evaluate different conditions on your documents.

Other common operators

  • $lt and $lte: To query documents with values less than or less than or equal to a specific number.
  • $eq and $ne: To find documents with values exactly equal to or different from the specified one.

Implementation of additional operators

To illustrate, here is an example using $lt:

db.students.find({ " age": { $lt: 20 } }).

In this query, we are selecting student documents where the age is less than 20.

Practical recommendations for queries in MongoDB

When working with MongoDB, it is crucial to develop a habit of properly structuring your data and queries to optimize performances and results. Here are some professional tips:

  • Index your collections: This will significantly improve the speed of your queries, especially when you employ comparison operators.
  • Evaluate the use of projections: Reducing the number of fields returned can optimize the operation.
  • Use multiple operators: Don't be afraid to combine different operators in the same query to achieve more accurate results.
  • Regularly analyze performance: Use MongoDB profiling tools to ensure that your queries are as efficient as possible.

By applying these methods and tips, you will become a master of MongoDB queries, transforming data into effective decisions for your business or personal project. Keep learning and exploring the infinite potential of NoSQL technology!

Contributions 10

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Operadores:

  • $gt (greater than - >)
  • $gte (greater than or equal - >=)
  • $lt (less than - <)
  • $lte (less than or equal - <=)

Mi pequeño aporte

// Using $gt (>: Mayor que) $gte (>= Mayor Igual)

// Traera los valores 25 y 30, pero no partira por el 20, asi cumple Mayor que 20
use("platzi_store")
db.inventory.find({ qty: { $gt: 20 } })

// Traera los valores 20, 25 y 30, sacara solamente el n°15 y asi cumple Mayor Igual que 20
use("platzi_store")
db.inventory.find({ qty: { $gte: 20 } })

// Using $lt (<: Menor que) $lte (<= Menor Igual)

// Traera solo el valor 15 y excluiria todos los otros valores
use("platzi_store")
db.inventory.find({ qty: { $lt: 20 } })

// Traera solo los valores 15 y 20 del documento y excluiria todos los otros valores
use("platzi_store")
db.inventory.find({ qty: { $lte: 20 } })

// Join - Traer todo los archivos que sean Mayor igual 25 y Menor igual 35 = El resultado debe ser 25 y 30
use("platzi_store")
db.inventory.find({ qty: { $gte: 25, $lte: 35 } })

// Join - Traer todo los archivos que sean Mayor igual 20 y Menor igual 35 = El resultado debe ser 20 y 25
use("platzi_store")
db.inventory.find({ qty: { $gte: 20, $lte: 25 } })

// New join

// Segun la condicional no hay ningun sub documento que tenga qty:20 y 25
use("platzi_store")
db.inventory.find({
    "item.name": "ab",
    qty: { $gte: 20, $lte: 25 }
})

// Segun la condicional solo aparecera un dato, porque solamente se encuentra en el code 123
use("platzi_store")
db.inventory.find({
    "item.code": "123",
    qty: { $gte: 20, $lte: 25 }
})

// Quiero que no busque mi sub documento 123 y si los demas que tengan qty Mayor Igual 20 y Menor Igual 25
use("platzi_store")
db.inventory.find({
    "item.code": { $ne: "123" },
    qty: { $gte: 20, $lte: 25 }
})

Solo porque en otros lenguales es mas intuitivo con los simbolos de matemáticas, pero aquí la lógica esta con las iniciales en inglés.

Hola,

En el minuto 9 al momento de hacer la consulta no se entendio porque no trajo los datos a consultar, solo debia cambiar el rango de qty para traer el “ab” del rango,

adjunto code, el curso esta muy chebre !!

db.inventory.find({ 
    "item.name": "ab",
    qty: { $gte: 15, $lte: 20 }
    })

Gracias !!

Aquí va mi aporte

// Using $gt (>: Mayor que) $gte (>= Mayor Igual)

// Traera los valores 25 y 30, pero no partira por el 20, asi cumple Mayor que 20
use("platzi_store")
db.inventory.find({ qty: { $gt: 20 } })

// Traera los valores 20, 25 y 30, sacara solamente el n°15 y asi cumple Mayor Igual que 20
use("platzi_store")
db.inventory.find({ qty: { $gte: 20 } })

// Using $lt (<: Menor que) $lte (<= Menor Igual)

// Traera solo el valor 15 y excluiria todos los otros valores
use("platzi_store")
db.inventory.find({ qty: { $lt: 20 } })

// Traera solo los valores 15 y 20 del documento y excluiria todos los otros valores
use("platzi_store")
db.inventory.find({ qty: { $lte: 20 } })

// Join - Traer todo los archivos que sean Mayor igual 25 y Menor igual 35 = El resultado debe ser 25 y 30
use("platzi_store")
db.inventory.find({ qty: { $gte: 25, $lte: 35 } })

// Join - Traer todo los archivos que sean Mayor igual 20 y Menor igual 35 = El resultado debe ser 20 y 25
use("platzi_store")
db.inventory.find({ qty: { $gte: 20, $lte: 25 } })

// New join

// Segun la condicional no hay ningun sub documento que tenga qty:20 y 25
use("platzi_store")
db.inventory.find({
    "item.name": "ab",
    qty: { $gte: 20, $lte: 25 }
})

// Segun la condicional solo aparecera un dato, porque solamente se encuentra en el code 123
use("platzi_store")
db.inventory.find({
    "item.code": "123",
    qty: { $gte: 20, $lte: 25 }
})

// Quiero que no busque mi sub documento 123 y si los demas que tengan qty Mayor Igual 20 y Menor Igual 25
use("platzi_store")
db.inventory.find({
    "item.code": { $ne: "123" },
    qty: { $gte: 20, $lte: 25 }
})
use("platzi_store")

/*Operadores de comparación
    • $gt (greater than)
    • $gte (greater than or equal)
    • $lt (less than)
    • $lte (less than or equal) */

//Busquedas usando operadores de comparación individualmente
db.inventory.find({qty: {$gt: 20}})
db.inventory.find({qty: {$gte: 20}})
db.inventory.find({qty: {$lt: 20}})
db.inventory.find({qty: {$lte: 20}})

// Combinación de operadores 
//Mayor o igual a 25 y menor o igual a 35
db.inventory.find({qty: {$gte: 25, $lte: 35}})

//Podemos hacer un "join", combinación de filtro con operadores de comparación
/* Aquí estamos poniendo dos condicionales: item.name (un subdocumento) con 
el valor de "ab" y los operadores de comparación: $gte y $lte.
En este caso no hay ni un documento que cumpla con ambas condiciones*/
db.inventory.find({"item.name": "ab", qty: {$gte: 20, $lte: 25}})

/*Otro ejemplo usando los operadores $ne (not equal) $gte y $lte
"Buscar los documentos cuyo field code en el subdocumento no sea igual a 123 y 
que la cantidad (qty) sea mayor o igual a 20 y menor o igual a 25"*/
db.inventory.find({"item.code": {$ne: "123"}, qty: {$gte: 20, $lte: 25}})
```js use("platzi_store") //Combinando operadores db.inventory.find({ qty: { $lte: 35, $gte: 25} }) db.inventory.find({ "item.name": "xy", qty: { $lte: 35, $gte: 25} }) ```use("platzi\_store") //Combinando operadores db.inventory.find({ qty: { $lte: 35, $gte: 25} }) db.inventory.find({ "item.name": "xy", qty: { $lte: 35, $gte: 25} })
```js // Inserta un documento en una colección db.users.insertOne({ name: "Juan", age: 25, email: "[email protected]", created_at: new Date() }); ```
Muy bien explicado todo. Super!!!
` ``` javascript ` `// Inserta un documento en una colección db.users.insertOne({ name: "Juan", age: 25, email: "[email protected]", created_at: new Date() });` ` ``` `