'How to retrieve a Mongo document based on the value of an element in a List field with Python
I have a MongoDB collection with documents that have a text field and list field :
db = client.PraxisDB
db.create_collection('Test')
I enter three documents into it
kollection = db.Test
kollection.insert_one({'text1': 'aaa','list1' : [' ',1,2,3,4]})
kollection.insert_one({'text1': 'bbb','list1' : [' ',1,6,7,8]})
kollection.insert_one({'text1': 'ccc','list1' : [' ',19,10,11,12]})
I can see that all are properly inserted
c = kollection.find()
for crnt in c:
print(crnt)
---
{'_id': ObjectId('61e543057aeccaf5a5345073'), 'text1': 'aaa', 'list1': [' ', 1, 2, 3, 4]}
{'_id': ObjectId('61e543057aeccaf5a5345074'), 'text1': 'bbb', 'list1': [' ', 1, 6, 7, 8]}
{'_id': ObjectId('61e543057aeccaf5a5345075'), 'text1': 'ccc', 'list1': [' ', 19, 10, 11, 12]}
I can retrieve individual records ONLY IF i specify the whole list
c = kollection.find({'list1': {'$eq': [' ',1, 2, 3, 4]}},{'_id':0})
for crnt in c:
print(crnt)
-----
{'text1': 'aaa', 'list1': [' ', 1, 2, 3, 4]}
I wish to retrieve the two docs that have value of 1 in the second element of the list field. For this I tried :
c = kollection.find({'list1'[1]: {'$eq': 1}},{})
for crnt in c:
print(crnt)
This query returned no documents. How should I change my query? Please help
Solution 1:[1]
Found a way to do this.
c = kollection.find({'list1.1': {'$eq': 1}},{'_id':0})
for crnt in c:
print(crnt)
-----
{'text1': 'aaa', 'list1': [' ', 1, 2, 3, 4]}
{'text1': 'bbb', 'list1': [' ', 1, 6, 7, 8]}
Should have been obvious! But it wasnt to me
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Calcutta |