Home > Mobile >  mongodb query to filter the array of objects using $gte and $lte operator
mongodb query to filter the array of objects using $gte and $lte operator

Time:03-02

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.

CodePudding user response:

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

CodePudding user response:

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 matching array elements, here's another way to do it.

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

Try it on mongoplayground.net.

  • Related