pymongo sort and find_one issue - python

I am trying to sort a collection called user_score using the key position and get the very first document of the result. In this case the collection user_score doesn't exist and I was hoping to get the result as None, but i was getting a cursor back.
1.
result =
db.user_score.find({'score':'$lt':score}}).sort("position,pymongo.DESCENDING").limit(1)
Now i changed my query like below and did not get anything as expected.
2.
result =
db.user_score.find_one({'score':{'$lt':score}}, sort=[("position", pymongo.DESCENDING)])
What's the problem with my first query?
Thanks

A little late in my response but it appears that the current version of PyMongo does support a sort operation on a find_one call.
From the documentation page here:
All arguments to find() are also valid arguments for find_one(),
although any limit argument will be ignored. Returns a single
document, or None if no matching document is found.
Example usage is as follows:
filterdict = {'email' : 'this.is#me.com'}
collection.find_one(filterdict, sort=[('lastseen', 1)])
Hope this helps more recent searchers!

In your first query, in the sort function you're passing one argument ("position,pymongo.DESCENDING"), when you should be passing two arguments ("position", pymongo.DESCENDING).
Be sure to mind your quotation marks.

This is the default mongodb behavior on find. Whenever you use find you get a list of the result (in this case an iterable cursor). Only findOne - or it's PyMongo equivalent find_one will return None if the query has no matches.

Use list to convert the value of the cursor into a dict:
list(db.user_score.find({'score':'$lt':score}}).sort("position",pymongo.DESCENDING).limit(1))[0]

Related

Datastore query sort order by newest date

I've read the documentation on how to do this but it is not working. I am trying to get my query to sort by date newest first, but this is not working:
wrQuery = WorkRequest.query()
wrQuery.order('-date')
wrResult = wrQuery.fetch()
I have also tried ('-WorkRequest.date') but both results in similar errors:
TypeError: order() expects a Property or query Order; received '-date'
The query objects are immutable, your 3rd statement references the object from your 1st statement, not the ordered one created in the 2nd statement. See also NDB Query builder doesn't work as expected.
This should work instead:
wrQuery = WorkRequest.query()
wrOrderedQuery = wrQuery.order('-WorkRequest.date')
wrResult = wrOrderedQuery.fetch()
This looks like you are using NDB rather than DataStore, in which case the docs show you unequivocally how to do it. This should work:
wrQuery = wrQuery.order(-WorkRequest.date)

meaning of distinct and how to use it in python(pymongo)

I don't understand what is the meaning of distinct and how use of it. i have search for related answer but it seems like distinct is somehow related to list. really appreciate the help.
list_of_stocks = db.stocks.distinct("symbol")
As the OP confirmed, this is a PyMongo call to a MongoDB database, which allows for a distinct find, in the form of:
db.collection_name.distinct("property_name")
This returns all distinct values for a given property in a collection.
Optionally, if you specify a document filter (effectively a find() filter) as a second parameter, your query will first be reduced by that filter, then the distinct will be applied. For example:
list_of_stocks = db.stocks.distinct("symbol", {"exchange": "NASDAQ"})
Distinct keyword is used in DB and it is to return record set only with distinct elements for that particular column.

Django SQL get query returns a <key, value> hashmap, how to access the value?

I am using django 1.10 and python 3.6.1
when executing
get_or_none(models.Character, pk=0), with SQL's get method, the query returns a hashmap i.e.: <Character: example>
How can I extract the value example?
I tried .values(), I tried iterating, I tried .Character
nothing seems to work, and I can't find a solution in the documentation.
Thank you,
get_or_none or returns model object or None if id does not exists. You an access it like any other model object and access it fields and methods
character = get_or_none(models.Character, pk=0)
character.some_field
if it is none you will get error if you try to access field
You can also try:
try:
obj = Character.objects.get(pk=1)
character = obj.somefield
except Character.DoesNotExist:
character = None
#Daniel Roseman helped me understand the answer.
SOLVED:
What I was getting from the query was the model of character, so I couldn't have accessed it thru result.Character but thru result.Field_Inside_Of_Character

PyMongo, Graphing

I have several mongo databases (some populated with collections and documents, some empty) and I am trying to parse through them and create a graph for the contents. I am planning on making nodes for each db, each collection, and each key in the collection, and the from each key to the value (so skipping the pages). Here is my code for getting the graph.
for db in dbs:
G.add_node(db)
for col in c[db].collection_names():
G.add_node(col)
G.add_edge(db, col, weight = 0.9)
for page in c[db][col].find():
if (u'_id' in page.viewvalues()):
pprint.pprint(page)
G.add_node(page[u'_id'])
G.add_edge(col, page[u'_id'], weight = 0.4)
for key, value in page.items():
G.add_node(key)
G.add_edge(col, key, weight = 0.1)
G.add_node(value)
G.add_edge(key,value)
My Problem is that I never pass the if statement if (u'_id' in page.viewvalues()): I know I am getting pages (if I print the pages before the if statement I get a few thousand printed but the if statement is always false. What have I done wrong in accessing the dictionary returned from the find() query? Thanks.
EDIT:
I should probably also mention that when I do something like this
for i in page:
instead of the of the if statement it works for a bit and then breaks saying TypeError: unhashable type: 'dict' and I figured this was when it hit an empty page or when find() returned no pages.
This works for me:
import pymongo
c = pymongo.Connection()
dbs = c.database_names()
for db in dbs:
for col in c[db].collection_names():
for page in c[db][col].find():
if '_id' in page:
for key, value in page.iteritems():
print key, value
You always get a dictionary while iterating over pymongo cursor (which is returned by find()). So, you can just check if there is an _id key in the dictionary.
By the way, you can specify what fields to see in the results by providing the fields argument to the find().

Return the column names from an empty MySQL query result

I'm using Python 3.2.3, with the MySQL/Connector 1.0.7 module. Is there a way to return the column names, if the MySQL query returns an empty result?
For example. Say I have this query:
SELECT
`nickname` AS `team`,
`w` AS `won`,
`l` AS `lost`
WHERE `w`>'10'
Yet, if there's nobody over 10, it returns nothing, obviously. Now, I know I can check if the result is None, but, can I get MySQL to return the column name and a NULL value for it?
If you're curious, the reason I'm wondering if this is possible, is because I'm dynamically building dict's based on the column names. So, the above, would end up looking something like this if nobody was over 10...
[{'team':None,'won':None,'lost':None}]
And looks like this, if it found 3 teams over 10...
[{'team':'Tigers','won':14,'lost':6},
{'team':'Cardinals','won':12,'lost':8},
{'team':'Giants','won':15,'lost':4}]
If this kind of thing is possible, then I won't have to write a ton of exception checks all over the code in case of empty dict's all over the place.
You could use a DESC table_name first, you should get the column names in the first column
Also you already know the keys in the dict so you can construct yourself and then append things to it if the result has values.
[{'team':None,'won':None,'lost':None}]
But what I fail to see why you need this. If you have a list of dictionaries, I am guessing you will have for loop operations. For loop will not do anything to a empty list, so you would not have to bother about exception checks
If you have to do something like result[0]['team'] then you should definitely check if len(result)>0

Categories