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?
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.
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.
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.
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With