Home > Net >  Query for more than one text value in a field, MongoDB
Query for more than one text value in a field, MongoDB

Time:03-07

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}})

CodePudding user response:

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

mongoplayground

  • Related