Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

650
Vistas
mongodb query to filter the array of objects using $gte and $lte operator

My doucments:

[{
  "_id":"621c6e805961def3332bcf97",
  "title":"monk plus",
  "brand":"venture electronics",
  "category":"earphones",
  "variant":[
      {
         "price":1100,
         "impedance":"16ohm"
      }, 
      {
        "price":1600,
        "impedance":"64ohm"
      }],
 "salesCount":185,
 "buysCount":182,
 "viewsCount":250
},
{
 "_id":"621c6dab5961def3332bcf92",
 "title":"nokia1",
 "brand":"nokia",
 "category":"mobile phones",
 "variant":[
      {
        "price":10000,
        "RAM":"4GB",
        "ROM":"32GB"
      },
      {
        "price":15000,
        "RAM":"6GB",
        "ROM":"64GB"
       }, 
      {
        "price":20000,
        "RAM":"8GB",
        "ROM":"128GB"
    }],
   "salesCount":34,
   "buysCount":21,
   "viewsCount":80
}]

expected output

 [{
    _id:621c6e805961def3332bcf97
    title:"monk plus"
    brand:"venture electronics"
    category:"earphones"
    salesCount:185
    viewsCount:250
    variant:[
              {
                price:1100
                impedance:"16ohm"
               }]
}]

I have tried this aggregation method

[{
  $match: {
     'variant.price': {
      $gte: 0,$lte: 1100
      }
   }}, 
{
  $project: {
        title: 1,
        brand: 1,
        category: 1,
        salesCount: 1,
        viewsCount: 1,
   variant: {
         $filter: {
             input: '$variant',
             as: 'variant',
             cond: {
                 $and: [
                    {
                      $gte: ['$$variant.price',0]
                    },
                    {
                      $lte: ['$$variant.price',1100]
                    }
                   ]
                }
              }
            }
         }}]

This method returns the expected output, now my question is there any other better approach that return the expected output.Moreover thank you in advance, and as I am new to nosql database so I am curious to learn from the community.Take a note on expected output all properties of particular document must return only the variant array of object I want to filter based on the price.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

your solution is good, just make sure to apply your $match and pagination before applying this step for faster queries

over 4 years ago · Santiago Trujillo Denunciar

0

There's nothing wrong with your aggregation pipeline, and there are other ways to do it. If you just want to return matching documents, with only the first matching array element, here's another way to do it. (The .$ syntax only returns the first match unfortunately.)

db.collection.find({
  // matching conditions
  "variant.price": {
    "$gte": 0,
    "$lte": 1100
  }
},
{
  title: 1,
  brand: 1,
  category: 1,
  salesCount: 1,
  viewsCount: 1,
  // only return first array element that matched
  "variant.$": 1
})

Try it on mongoplayground.net.

Or, if you want to use an aggregation pipeline and return all matching documents in entirety except for the filtered array, you could just "overwrite" the array with the elements you want using "$set" (or its alias "$addFields"). Doing this means you won't need to "$project" anything.

db.collection.aggregate([
  {
    "$match": {
      "variant.price": {
        "$gte": 0,
        "$lte": 1100
      }
    }
  },
  {
    "$set": {
      "variant": {
        "$filter": {
          "input": "$variant",
          "as": "variant",
          "cond": {
            "$and": [
              { "$gte": [ "$$variant.price", 0 ] },
              { "$lte": [ "$$variant.price", 1100 ] }
            ]
          }
        }
      }
    }
  }
])

Try it on mongoplayground.net.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda