0

For a document with fields:

{"_id" : 1, "name": "Sarah", "fruitEaten" : ["apple", "banana", "orange"]}

{"_id" : 2, "name": "Steve", "fruit Eaten" : "apple"}

{"_id" : 3, "name": "Stacey", "fruitEaten" : ["apple", "orange"]}

How can I query to get who ate more than one fruit eaten?

I have been trying db.collection.find({"fruitEaten":{"$gt":1},{"name":1}})

kedoink
  • 81
  • 1
  • 7
  • Does this answer your question? [Query for documents where array size is greater than 1](https://stackoverflow.com/questions/7811163/query-for-documents-where-array-size-is-greater-than-1) – Dharmaraj Mar 06 '22 at 10:55
  • no unfortunately not, because I have realised all the fields aren't arrays – kedoink Mar 06 '22 at 11:23

1 Answers1

3
db.collection.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          {
            $isArray: "$fruitEaten"
          },
          {
            $gt: [ { $size: "$fruitEaten" }, 1 ]
          }
        ]
      }
    }
  }
])

mongoplayground

YuTing
  • 6,555
  • 2
  • 6
  • 16
  • Thanks this is definitely helpful, I realised I was getting an error because not all the fields are arrays? And when trying "this.fruitEaten.length" those not in an array form I believe are counted by characters! Any suggestions? – kedoink Mar 06 '22 at 11:25
  • @kedoink I update my answer. – YuTing Mar 06 '22 at 11:41