Search code examples
pythonjsontinydbnosql

TinyDB get all IDs in list query


I'm using TinyDB in my python project. However, in order to make the logic effective, I need to be able to get multiple objects in a query. My preference would be to use a list

listOfIDs = ['123', '456']

I am using the latest Python version and TinyDB implementation.

I have the following implementation:

from tinydb import TinyDB, Query
db = TinyDB('db.json')
myDBQuery= Query()
db.insert({'id': '123', 'name': 'bob'})
db.insert({'id': '456', 'name': 'mary'})
result = db.search(myDBQuery.id.all(['123', '456']))
print(result)

However, I keep getting the following as a result:

[]

I know my implementation is working because when I do the following, I get the expected results:

result = db.search((myDBQuery.id == '123') | myDBQuery.id == '456'))

Anyone know how to query with a list in TinyDB?

Anyone know how to query with a list in TinyDB?

EDIT

For those of you wondering, there isn't a way to do it with the current implementation. My only workaround is to create something like the following

def getAllObjectsMatchingId(listOfIds):

tempList = []

for idMember in tempList:
    result = db.search(myDBQuery.id == idMember)
    tempList.append(result)

return tempList

Solution

  • .all returns true only if all the elements of the list match the query

    .any might work instead

    result = db.search(myDBQuery.id.any(['123', '456']))
    

    EDIT FROM QUESTION OP: Please see my edit above