1

I'd like to retrieve all documents from a MongoDB collection, where users field is either numeric or a string, consisting of all digits (1, 2, 19, or "4", "19", ...)

I query:

db.getCollection('collection').find(
    { 
        users: { $or : [ { $type: [1, 16, 18, 19] },
                         { $regex: /^[0-9]+$/ } ]
               }
    }
)

... and get the error "Unknown operator $or".

This works:

db.getCollection('collection').find(
    { 
        $or: [ 
                {users:  { $type: [1, 16, 18, 19] } },
                {users:  { $regex: /^[0-9]+$/ }}
        ]
    }
)

Why doesn't the first variant work?

wl2776
  • 4,099
  • 4
  • 35
  • 77

2 Answers2

3

$or must itself contains the field upon which you want to query. Your second query contains the field.

$or :[{field_name:Match_expression},{field_name:Match_expression}...{field_name:Match_expression}]
mehta-rohan
  • 1,373
  • 1
  • 14
  • 19
0
db.getCollection('collection').find( {
    $and : [
        { $or : [ { $type: [1, 16, 18, 19] } ] },
        { $or : [ {users:  { $regex: /^[0-9]+$/ } ] }
    ]
} )

this should work

EDIT

This is where it was answered before

damirljub
  • 307
  • 2
  • 9
  • This gives error "unknown top level operator: $type" – wl2776 Jun 27 '18 at 11:43
  • And linked answer describes another problem. Linked answers cites the manuals that say that `$and` can be omitted in certain circumstances ("implicit `$and`"). It looks like similar thing for `$or` is simply not implemented. – wl2776 Jun 27 '18 at 12:15