Fluidbyte
Fluidbyte

Reputation: 5210

MongoDB find records with empty array or array match

I have a set of records like the following:

[ 
  { title: 'foo', members: [ 'a', 'b' ] },
  { title: 'bar', members: [] },
  { title: 'fiz', members: [ 'b' ] }
]

The members prop is used for restricting certain records so what I'm hoping to do is check the property and if empty or doesn't exist OR it contains the member return the item.

For example:

Upvotes: 3

Views: 165

Answers (1)

Valijon
Valijon

Reputation: 13103

Something like this:

db.collection.find({
  $or: [
    {
      "members.0": {
        $exists: false
      }
    },
    {
      "members": "User"
    }
  ]
})

MongoPlayground

or

db.collection.find({
  $or: [
    {
      $expr: {
        $eq: [
          {
            $size: "$members"
          },
          0
        ]
      }
    },
    {
      "members": "User"
    }
  ]
})

Upvotes: 3

Related Questions