简体   繁体   中英

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.

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}}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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