简体   繁体   English

查询以在 pymongo 中查找嵌套字典

[英]Query to find nested dictionary in pymongo

I have nested dictionary which i inserted in my collection我在我的收藏中插入了嵌套字典

data={'name': {'animal': {'lion': 2, 'tiger': 1}}}
data1={'name': {'plant': {'herb': 2, 'tree': 1}}}
collection.insert_one(data)
collection.insert_one(data1)

collection.find({})

It is giving me the output as.它给了我输出。

[{'_id': ObjectId('5fabab4c959bc806cd129d6a'),
  'name': {'plant': {'herb': 2, 'tree': 1}}},
 {'_id': ObjectId('5fabb0a2959bc806cd129d6b'),
  'name': {'animal': {'lion': 2, 'tiger': 1}}}]

I have a two list one is name and other one is token.我有两个列表,一个是名称,另一个是令牌。

name=["animal","ocean"]
token=["fish","desert","lion"]

Now my query is that first i will check if name is present in our collection or not if name is not present that we simply insert dictionary in collection like this.现在我的查询是,首先我将检查名称是否存在于我们的集合中,如果名称不存在,我们只需像这样在集合中插入字典。 (ocean is not present in collection) (海洋不存在于集合中)

data={'name': {'ocean': {'fish': 1, 'desert': 1,"lion":1}}}
collection.insert_one(data)

if name is present in our collection then we will check how many token is present if token is present we will increase its count otherwise it will be so for animal we will insert.如果 name 存在于我们的集合中,那么我们将检查存在多少令牌,如果存在令牌,我们将增加其计数,否则我们将插入动物。

data={'name': {'animal': {'fish': 1, 'desert': 1,"lion":2}}}

My solution is that first check if the name is present in collection or not if it is present than just fetch it and update it by iterating over dictionary.我的解决方案是首先检查名称是否存在于集合中,如果它存在,则不仅仅是获取它并通过迭代字典来更新它。 I tried to check if name is present or not by.我试图检查名称是否存在。

list(collection.find({"name.1":"animal"}))

But it is giving me empty list.但它给了我空列表。 What is the correct way to solve the query?解决查询的正确方法是什么?

如果要检查对象中是否存在键,请使用$exists运算符:

list(collection.find({"name.animal": {"$exists": True}}))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM