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?

2 Answers 2

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" }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.