Query to a List of dictionaries, return the specific dictionary?

空扰寡人 提交于 2019-12-11 17:39:38

问题


I pushed a db as simple as, using python, pymongo and mnogodb, the db is mae of many files like the sample below:

  def pushdata():
        for filename in os.listdir(directory):        
                with open( directory + filename , 'r') as f:
                    datastore = json.load(f)
                    m = data.insert_one(datastore) 

My jsons loook like that

  {
            "info": {
                "S1": {
                    "SS": "1221"
                },
                "S2": {
                    "SDS011": "5121"
                },
                "OP": "157.138",
                "LK": "32121",
                "MN": "122.077"
            },
            "readings": [
                {
                    "SS1": "7.80",
                    "SS2": "1.80",
                    "timestamp": "1530857160"
                },
                {
                    "SS1": "9.67",
                    "SS2": "2.53",
                    "timestamp": "1530857520"
                },
            ]
        }

how can i query the data? When i try

  print(data.find_one({'$and':[{ "readings.SS1": "7.80"},
                {"readings.SS2": "1.80"}]})) 

in python

 print(data.find_one( "readings.SS1": "7.80"}))

in mongodb

I always get the whole Database file not the specific dictionary from the list? Why does it happen? I want query response like that:

   {
                "SS1": "7.80",
                "SS2": "1.80",
                "timestamp": "1530857160"
            }

also for the info dictionary, how to make a query where let say 'OP'=157.138 and 15500000< timestamp < 15000000 , response:

  {
        "SS1": "7.80",
        "SS2": "1.80",
        "timestamp": "15100000"
    }
    {
        "SS1": "7.80",
        "SS2": "1.80",
        "timestamp": "15300000"
    }
    {
        "SS1": "7.80",
        "SS2": "1.80",
        "timestamp": "15500000"


   }

回答1:


You can use an aggregation like below:

db.collection.aggregate([
  {$unwind: "$readings"},
  {$match: {"readings.SS1": "7.80"}},
  {$replaceRoot: {newRoot: "$readings"}}])

Which returns:

[
  {
    "SS1": "7.80",
    "SS2": "1.80",
    "timestamp": "1530857160"
  }
]


来源:https://stackoverflow.com/questions/58936396/query-to-a-list-of-dictionaries-return-the-specific-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!