简体   繁体   中英

How pymongo define the key for append the value

Mongodb collections like this:

 `col={"a":{"x":1,"y":2},"b":[{"w":5,"z":7},{"w":8,"z":5}]}`

It works in pymongo:

 `col.find({"a.x":1}) or col.find({"b.w":5})`

now I want create a list to append the value of the key like "ax" or "bw",I write the code as follows,but get noting.

 `data1=[]
 data2=[]
 finddata={}
 for data in col.find({}):
    finddata=dict(data)
    for key,value in finddata.items():
       if key == "a.x":      #if key=="a" will works
          data1.append(value)
       if key == "b.w":
          data2.append(value)`

Can anyone help me?Thanks

Using Mongo aggregation pipeline, the fields you care about can be projected and made to replace the returned fields in the returned root document. eg

pipeline = [
    {'$project': {'a.x':1, 'b.w': 1}},
    {'$replaceRoot': {'newRoot': {'a_x': '$a.x', 'b_w': '$b.w'}}}
] 

cur = db.keyes.aggregate(pipeline)
result = next(cur)

This way, you can go ahead to extend the respective lists using the result.

tolist = lambda x: x if isinstance(x, list) else [x]

data1.extend(tolist(result['a_x']))
data2.extend(tolist(result['b_w']))
I finally found the best way to solve this problem,Create a Dict of data that find in database.then define the key that you want choose as 'objkey'
dictA={"a":{"x":1,"y":2},"b":[{"w":5,"z":7},{"w":8,"z":5}]}
value=get_dict_in(dictA,'x',None)

eg

 dictA={"a":{"x":1,"y":2},"b":[{"w":5,"z":7},{"w":8,"z":5}]} value=get_dict_in(dictA,'x',None) 

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