Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the json object with only 2 or more bananas in the fruits array?

I have this mongoose schema.

const storeSchema = mongoose.Schema({
    name: {
        type: String,
        required: true,
    },
    fruits: {
        type: [String],
        required: true,
    },
});

And I need to get all the objects that have 2 or more bananas in the fruits array, like this.

{
    "name": "Beautiful Store",
    "fruits": ["banana", "apple", "banana", "pear"]
}

I was trying something like this, but with no success…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const query = await StoreModel.find({ fruits: { $gd: 2 } })

>Solution :

Somethign like this:

Option 1: ( less efective but intuitive )

  db.collection.aggregate([
  {
   $addFields: {
    numBananas: {
    $size: {
      $filter: {
        input: "$fruits",
        as: "item",
        cond: {
          $eq: [
            "$$item",
            "banana"
          ]
         }
       }
      }
     }
    }
   },
  {
   $match: {
     numBananas: {
        $gte: 2
      }
    }
   },
  {
    $project: {
       name: 1,
       fruits: 1
   }
  }
 ])

Explained:

  1. Add field "numBananas" with the number of bananas
  2. Filter only the document having >=2 banas
  3. Project only the necessary output

playground

Option 2: ( Best , inspired by Buzz below 🙂 )

 db.collection.aggregate([
 {
  $match: {
   $expr: {
    $gte: [
      {
        $size: {
          $filter: {
            input: "$fruits",
            as: "item",
            cond: {
              $eq: [
                "$$item",
                "banana"
              ]
            }
          }
        }
      },
      2
     ]
    }
   }
  }
])

Explained:
Just match those having >=2 bananas , best if index created on fruits
( I think this solution is in 50/50 performance competition with the $reduce option from Buzz below )

playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading