3

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:

  • User a would get back foo (is a member) and bar (no member restrictions)
  • User b would get all three because they are a member on 0 and 2 and no member restrictions are set on on 1
1
  • Try var user = 'a'; db.collection.distinct('title', { '$or': [ { 'members': user }, { 'members.0': { '$exists': false } } ] }); Commented Feb 12, 2020 at 16:45

1 Answer 1

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.