【发布时间】:2020-12-13 06:42:11
【问题描述】:
我正在使用 pymongo 访问我的 MongoDB 中的文档。 现在我想根据值标准是否为真过滤返回的目录。
目前我的代码如下所示:
db = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = db.myclient["pricing"]
mycol = mydb["locations"]
mydoc = db["pricing"]["prices"].find_one({"location":"test"})
for i in mydoc.items():
print(i)
此代码返回以下内容:
('_id', ObjectId('5f43c555dec06035ccfd2eac'))
('location', 'test')
('rent-40', {'titel': 'Base rent', 'price': 620, 'tooltip': 'test i think ', 'explenation': 'longer explanation', 'standard': False})
('rent-32', {'titel': 'Base rent', 'price': 600, 'tooltip': 'nana', 'explenation': 'very long explenation', 'standard': True})
('water', {'titel': 'Water cost', 'price': 10, 'tooltip': 'test', 'explenation': 'long explenation', 'standard': True})
('tv-38', {'titel': 'TV program', 'price': 5, 'tooltip': 'long', 'explenation': 'longer', 'standard': False})
('tv-70', {'titel': 'TV program', 'price': 5, 'tooltip': 'boring', 'explenation': 'very boring', 'standard': True})
最终结果应该是standard == True 所在的字典列表。
非常感谢您在这方面的帮助,因为我正在努力解决数据的嵌套问题。
也许不是最优雅的解决方案,但它对我有用。问题是前两个项目的格式不同,所以我把它们剪掉了,然后它就很简单了:
standard = []
c =list(mydoc.items())
#print(c[2:])
for i in c[2:]:
if i[1]["standard"] == True:
standard.append(i)
else:
print("hi")
print(standard)
【问题讨论】:
标签: python dictionary filter pymongo