Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query list in Pymongo

I have this code in Python:

import datetime
import re
import pymongo
from datetime import timedelta, date

def daterange(d, d1):
    for n in range(int ((d1 - d).days)):
        yield d + timedelta(n)

#conect to db
uri = "mongodb://127.0.0.1:27017"
client = pymongo.MongoClient(uri)
database = client['db']
collection = database['currency']


d = input('Insert beginning date (yyyy-mm-dd): ')
d1 = input('Insert end date (yyyy-mm-dd): ')

#search db
item = collection.find_one({"date" : d})
item1 = collection.find_one({"date" : d1})
d = collection.find_one({})
d1 = collection.find_one({})
datas = item['date']
datas1 = item1['date']

#convert string to object
dataObject = datetime.datetime.strptime(datas, "%Y-%m-%d")
dataObject1 = datetime.datetime.strptime(datas1, "%Y-%m-%d")


#range
mylist = []
for single_date in daterange(dataObject, dataObject1):
    mylist.append(single_date.strftime("%Y-%m-%d"))
    print(single_date.strftime("%Y-%m-%d"))
print(mylist)
item = collection.find_one({"date" : mylist[0]})
print(item)

If a user inserts a beginning date like 2018-05-07 and an end date like 2018-05-11 it will print:

2018-05-07
2018-05-08
2018-05-09
2018-05-10

And the printed dates will go to mylist. What I want to know how to find the dates in mylist that are in my mongoDB, I could do one by one, but that wouldn't work if the user inserted more dates.

like image 528
Filipe Varandas Avatar asked Sep 11 '25 07:09

Filipe Varandas


1 Answers

You can use the $in operator to query for all values in an array. You also need to iterate over your results since the find() call returns a cursor:

for item in collection.find({"date" : {"$in": mylist}}):
    print(item)
like image 66
dnickless Avatar answered Sep 13 '25 07:09

dnickless