user8348955 user8348955 - 3 years ago 182
Python Question

how to get an input in Pymongo

I have a query, which needs to get an input "user" and then search. My code is:

import sys
import pymongo
import re
import codecs

from pymongo import MongoClient
client = MongoClient()

db = client['moviesdb']

user = input("Enter the user: ")

# #ratings = db.ratings

from bson.son import SON



# import pprint


cursor = db.ratings.distinct("MovieID",{"UserID":"user"});
# curson = db.ratings.distinct("UserID",{"MovieID":{"$in":a}});


for document in cursor:
print (document)


in the cursor, if I replace "user" with any number like 1 or 2, it works, but if I use "user" like the code above, it does not work.What is the problem? Also, if I have to use two queries to get the result, like the code above(but I comment the second query for now), what should I do? Thanks!

Answer Source

"user" vs user

"user" is a string. user is an identifier which evaluates to the value of the variable.

Try this:

cursor = db.ratings.distinct("MovieID",{"UserID":user}) # notice no quotes on `user`

You need to convert your input to an integer

Try user = int(input(...))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download