How can I check whether a specific field has two or more values? Pymongo, MongoDB

89 Views Asked by At

I have a question. Some background context: I am querying a database for a specific field whose value is of the type [User]. Where "User" is of type ObjectId(x) for some x. For example:

{  '_id': ObjectId(x)
   'field_1: value
   'field_2: [User_1]
}

However, field_2 can also have multiple Users within the brackets in other documents like so:

   'field_2': [User_1, User_2, User_3]

So my question is: If I need to narrow down the population, how can I search for the documents that have two or more "User" values in 'field_2'?

1

There are 1 best solutions below

0
On

You can use mongo query operators in order to narrow down your results.

For your purposes, a combination of $and, $size, and $not should work.

query = { '$and': [ 
    { 'field_2': { '$exists': 'true'} }, 
    { 'field_2': { '$not': { '$size':  0 } } },
    { 'field_2': { '$not': { '$size':  1 } } }
] } )
collection.find(query)