0

I have the following document:

{
    "_id": {
        "$oid": "5d4037f811b787414dcfb3a5"
    },
    "id": 1,
    "seats": [{
        "available": true
    }, {
        "available": true
    }, {
        "available": true
    }, {
        "available": false
    }]
}

How to query using mongodb-java-driver only the documents that have number of seats available greater than 3?

What I want is something like this: (seats.available eq true) gt 3

Is it possible?

ms1403
  • 13
  • 4

2 Answers2

1

i think this might be a duplicate to Query for documents where array size is greater than 1

so something like this i would guess:

{ $where: "this.seats.available.length > 3" }
deekim
  • 11
  • 3
0

To count the number of available seats, we can use $reduce aggregation stage. It would count the seats whose availability are marked as 'true'. In the next pipeline stage, the documents are filtered which have the count of available seats greater than 3.

db.checks.aggregate([
    {
        $addFields:{
            "availableSeats":{
                $reduce:{
                    "input":"$seats",
                    "initialValue": 0,
                    "in":{
                        $sum:[
                            "$$value",
                            {
                                $cond:[
                                    {
                                        $eq:["$$this.available",true]
                                    },
                                    1,
                                    0
                                ]
                            }
                        ]
                    }
                }
            }
        }
    },
    {
        $match:{
            "availableSeats":{
                $gte: 3
            }
        }
    }
]).pretty()
Himanshu Sharma
  • 2,940
  • 1
  • 7
  • 18