Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pymongo, query on list field, and/or

Tags:

I have a collection with some documents like:

{     _id: 5,     vals: [100, 1100, 1500] }, {     _id: 10,     vals: [1100, 1700] } 

How can I query for documents that have, in vals field:

  • 1100
  • 1700 OR 100
  • 100 AND 1100

I can use some comprehension magic like:

g = lambda codes: (     d for d in collection.find() if any(code in d["vals"] for code in codes) ) g([100, 1700]).next() 

Or, for the AND:

g = lambda codes: (     d for d in collection.find() if all(code in d["vals"] for code in codes) ) g([100, 1100]).next() 

This seems a little clunky though if there is some find magic that can be done with the driver.

like image 495
Skylar Saveland Avatar asked Aug 22 '12 00:08

Skylar Saveland


People also ask

What does $IN do in MongoDB?

The $in operator selects the documents where the value of a field equals any value in the specified array. To specify an $in expression, use the following prototype: { field: { $in: [<value1>, <value2>, ... < valueN> ] } } For comparison of different BSON type values, see the specified BSON comparison order.

How do you do and operation in MongoDB?

MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array.


1 Answers

yourmongocoll.find({"vals":1100}) yourmongocoll.find({"$or":[ {"vals":1700}, {"vals":100}]}) yourmongocoll.find({"$and":[ {"vals":100}, {"vals":1100}]}) 

i would recommend reading Mongodb Advanced queries

you will also find $in ...useful

like image 138
jassinm Avatar answered Oct 17 '22 16:10

jassinm