将变量传递到MongoDB查询

2024-10-02 10:24:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我的收藏有以下文件

{
  cust_id: "0044234",
  Address: "1234 Dunn Hill",
  city: "Pittsburg",
  comments : "4"
},

{
  cust_id: "0097314",
  Address: "5678 Dunn Hill",
  city: "San Diego",
  comments : "99"
},

{
  cust_id: "012345",
  Address: "2929 Dunn Hill",
  city: "Pittsburg",
  comments : "41"
}

我想写一段代码,提取并存储来自同一城市的所有客户id。我可以通过在MongoDB上运行以下查询得到答案:

^{pr2}$

但是,我无法使用Python实现相同的功能。以下是我尝试过的:

ctgrp=[{"$group":{"_id":"$city","number of cust":{"$sum":1}}}]
myDict={}
for line in collection.aggregate(ctgrp) : #for grouping all the cities in   the dataset
    myDict[line['_id']]=line['number of cust']
for key in myDict:
    k=db.collection.find({"city" : 'key'},{'cust_id:1'})
    print k
client.close()

而且,我也不知道如何存储这个。我唯一想到的就是一本字典,里面有一个对应于某个特定“键”的“值列表”。但是,我无法实现类似的实现,我正在寻找这样的输出

对于Pitsburg,值为0044234和012345。在


Tags: ofinidnumbercityforaddressline
1条回答
网友
1楼 · 发布于 2024-10-02 10:24:59

您可以使用^{}方法,这是最好的方法。在

import pymongo
client = pymongo.MongoClient()
db = client.test
collection = db.collection

然后:

^{pr2}$

产量:

^{3}$

或者在客户端执行无效的操作:

>>> cust_ids = set()
>>> for element in collection.find({'city': 'Pittsburg'}):
...     cust_ids.add(element['cust_id'])
... 
>>> cust_ids
{'0044234', '012345'}

现在,如果你想要一个城市的所有“客户身份证”就在这里

 >>> list(collection.aggregate([{'$match': {'city': 'Pittsburg'} }, {'$group': {'_id': None, 'cust_ids': {'$push': '$cust_id'}}}]))[0]['cust_ids']
['0044234', '012345']

现在,如果您想要的是按城市对文档进行分组,然后在这里找到不同的“客户id”,然后是:

>>> from pprint import pprint
>>> pipeline = [{'$group': {'_id': '$city', 'cust_ids': {'$addToSet': '$cust_id'}, 'count': {'$sum': 1}}}]
>>> pprint(list(collection.aggregate(pipeline)))
[{'_id': 'San Diego', 'count': 1, 'cust_ids': ['0097314']},
 {'_id': 'Pittsburg', 'count': 2, 'cust_ids': ['012345', '0044234']}]

相关问题 更多 >

    热门问题