Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo: how to use $or operator to an column that is an array?

I have a collection like this:

user_id     albums
1           [1 2 3 4]
2           [3 5 7 8]

I want to find out all the records that, the albums contains 3 or 7 or 8, I wrote the code like this but not working:

or_array = []
or_array.append({"albums":3})
or_array.append({"albums":7})
or_array.append({"albums":8})

collection1.find({"$or":or_array})

What is the right way to do this?

like image 934
Bin Chen Avatar asked Dec 27 '11 03:12

Bin Chen


People also ask

How do I query a field in an array in MongoDB?

Query an Array by Array LengthUse the $size operator to query for arrays by number of elements. For example, the following selects documents where the array tags has 3 elements.

How do you get a specific object from an array in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do I filter an array element in MongoDB?

Filter MongoDB Array Element Using $Filter Operator This operator uses three variables: input – This represents the array that we want to extract. cond – This represents the set of conditions that must be met. as – This optional field contains a name for the variable that represent each element of the input array.

How do I match an array in MongoDB?

Use $match With $all to Find Matching Documents in an Array in MongoDB. The $all is equivalent to the $and operator. This code retrieves all those documents where the courses array contains all the specified elements for the $all operator. The resulting documents must contain Java and Python elements.


1 Answers

try this

collection1.find({'albums': {'$in': [3, 7, 8]}})

from the mongodb docs, [IN] allow[s] you to specify an array of possible matches

If that doesn't work, maybe back track and look at the actual types of 3 7 and 8 in the collection to ensure they are ints.

print type(collection1.find_one()['albums'][0])
like image 54
dskinner Avatar answered Sep 23 '22 03:09

dskinner