Passing variables onto a MongoDB Query
Question: My collections has the following documents

    
    
    {
      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"
    }
    

I want to write a block of code that extracts and stores all cust_id's from
the same city. I am able to get the answer by running the below query on
MongoDB :

    
    
    db.custData.find({"city" : 'Pittsburg'},{business_id:1}). 
    

However, I am unable to do the same using Python. Below is what I have tried :

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

Also, I am unable to figure out how can I store this. The only thing that is
coming to my mind is a dictionary with a 'list of values' corresponding to a
particular 'key'. However, I could not come up with an implementation about
the same.I was looking for an output like this

For Pitssburg, the values would be 0044234 and 012345.


Answer: You can use the
[`.distinct`](http://api.mongodb.org/python/current/api/pymongo/cursor.html#pymongo.cursor.Cursor.distinct)
method which is the best way to do this.

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

then:

    
    
    collection.distinct('cust_id', {'city': 'Pittsburg'})
    

Yields:

    
    
    ['0044234', '012345']
    

or do this client side which is not efficient:

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

Now if you want all "cust_id" for a given city here it is

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

Now if what you want is group your document by city then here and find
distinct "cust_id" then here is it:

    
    
    >>> 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']}]
    

