Highest value(max) from mongodb collection error - Flask Python - python

I am trying to get the highest value for nr from a mongo database collection named prob that looks like this for now:
{
"_id": {
"$oid": "5ae9d062f36d282906c59736"
},
"nr": 1,
"nume": "numeunu",
"enunt": "-",
"datedeintrare": "-",
"datedeiesire": "-"
}
{
"_id": {
"$oid": "5ae9f190f36d282906c5b461"
},
"nr": 2,
"nume": "numedoi",
"enunt": "-",
"datedeintrare": "-",
"datedeiesire": "-"
}
My testing flask code is:
#app.route('/test')
def testaree():
prob = mongo.db.prob
return prob.find().sort({"nr":-1}).limit(1)
but it gives me an error TypeError: if no direction is specified, key_or_list must be an instance of list

The syntax for sorting using pymongo is different from the mongo query language.
In the above code the expression used is
sort({"nr":-1})
However , that is a mongo shell query syntax. When using pymongo it should be
sort("nr", pymongo.DESCENDING)
You could also use find_one instead of a limit clause once the data is sorted.
db.prob.find_one(sort=[("nr", pymongo.DESCENDING)])

Related

SQLAlchemyObjectType.Meta two models graphene

I am trying to combine two SQLAlchemyConnectionField. The current error i face is graphql.error.base.GraphQLError: Expected value of type "PostsObject" but got: Tag
My current connections are defined like so posts = SQLAlchemyConnectionField(PostsObject.connection, /* input arguments like posts(name: "") */) Is there a way to add another type or allow to return something like
"data": {
"posts": {
"edges": [
{
"node": "Different table"
},
{
"node": "Other table"
}]}},
I am using graphene_sqlalchemy well anyway thats all thanks !

How to fix 'parse error on (VAR_SIGN)' in a graphql query in python

I am having trouble with GraphQL queries made in python. It says that the signal $ that determine a variable in the query cannot be parsed.
Error message:
{"errors":[{"message":"Parse error on \"$\" (VAR_SIGN) at [3, 3]","locations":[{"line":3,"column":3}]}]}
Is there other way to use variables in this kind of request?
Here is my query, I didn't paste the fragment because I think it's not the problem
query ApplicationIndexQuery(
$status: Boolean!
$page: Int
$perPage: Int
$filters: ApplicationFilter
$sort: String
) {
allOpportunityApplication(page: $page, per_page: $perPage, filters: $filters, sort: $sort) {
...ApplicationList_list
}
}
variables = {
"status": True,
"page": 1,
"perPage": 517,
"filters": {
"date_realized": {
"from": "2018-12-01",
"to": "2019-03-31"
},
"person_home_mc": 1535,
"programmes": 5
}
query should be at the top level, but it seems like in your example it's enclosed in curly braces. See below:
https://github.com/apollographql/graphql-tag/issues/180#issuecomment-386540792

How to return only aggregation results not hits in elasticsearch query dsl

I am writing a query dsl in python using http://elasticsearch-dsl.readthedocs.io
and I have following code
search.aggs.bucket('per_ts', 'terms', field='ts')\
.bucket('load_time', 'percentiles', field='total_req', percents=[99])
response = search.execute()
This works fine but it also returns hits. But I don't want hits
In curl query mode I can get what I want by doing size:0 in
GET /twitter/tweet/_search
{
"size": 0,
"aggregations": {
"my_agg": {
"terms": {
"field": "text"
}
}
}
}
I couldn't find a way where I can use size = 0 in query dsl.
Referring to the code of elasticsearch-dsl-py/search.py here
s = Search().query(...).extra(from_=0, size=25)
This statement should work.

Database error from mongoengine max_distance query

Hi i have a problem with queries data using mongoengine. I try to do this same like in documentation but i have a problem.
I create two models
class Alarm(mongoengine.Document):
added = mongoengine.DateTimeField()
title = mongoengine.StringField()
tracks = mongoengine.ListField(mongoengine.EmbeddedDocumentField(Track))
meta = {
'indexes': [[("tracks.location", "2dsphere")]]
}
class Track(mongoengine.EmbeddedDocument):
created_on = mongoengine.DateTimeField()
location = mongoengine.PointField()
from django shell i add one row :
db.alarm.insert({"title": "Warszawa", "tracks": [{"location": {"type": "Point", "coordinates": [21.01666, 52.233333]}}]})
I connect to mongodb and from shell i try to find my new location using $near:
>db.alarm.find({'tracks.location': {$near: {$geometry: {"type": "Point", coordinates: [18.068611, 59.329444]}, $maxDistance: 810997}}})
>
> db.alarm.find({'tracks.location': {$near: {$geometry: {"type": "Point", coordinates: [18.068611, 59.329444]}, $maxDistance: 810998}}})
{
"_id" : ObjectId("53ef89626dda06655a57a342"), "title" : "Warszawa",
"tracks" : [ { "location" : { "type" : "Point", "coordinates" : [
21.01666, 52.233333 ] } } ] }
Returned result is that what i expected. First query return none second find my location.
But i cannot receive this same result using mongoengine
Alarm.objects(tracks__location__near = {"coordinates":[ 21.01666, 52.233333 ] , "type": "Point"}, tracks__location__max_distance=810998)
i get:
<repr(<mongoengine.queryset.queryset.QuerySet at 0x7ff3a50e8a10>) failed: pymongo.errors.OperationFailure: database error: Can't canonicalize query: BadValue geo near accepts just one argument when querying for a GeoJSON point. Extra field found: $maxDistance: 810998>
This is more like a hint, but:
$near operator in MongoDB has two subclauses: $geometry and $maxDistance (that's how you call it in the Mongo shell). But it looks like your custom object tries to instantiate $near clause with only $geometry as parameter.
So it's not tracks__location__max_distance, but rather something like tracks__location__near__max_distance (i.e. max_distance should be inside $near clause).

how to rewrite mongo shell code to regular python file?

The below code exist inside a python file I run at cli as 'python test.py '....
import pymongo
from pymongo import Connection
connection = Connection('localhost', 27017)
db = connection.school
data = db.students.aggregate(
{ $match : { 'scores.type': 'homework' },
{ $project: { id : $_id,
name : $name,
scores : $scores
},
{ $unwind: "$scores" },
{ $group : {
_id : "$id",
minScore: { $min :"$scores.score" },
maxScore: { $max: "$scores.score" }
}
});
for _id in data:
print _id
# NOTE: this can only be done ONCE...first find lowest_id then
# remove it by uncommenting the line below...then recomment line.
# db.students.remove(data)
when I run this code I get this error...
File "test.py", line 11
{ $match : { 'scores.type': 'homework' },
^
SyntaxError: invalid syntax
How do I rewrite this code so it works correctly from inside my test.py python file?
You have a few syntax issues.
First, pipeline is an array (a list in Python) where you are trying to pass multiple pipeline elements as separate parameters.
Second, you need to quote the pipeline operators, such as $match: '$match'
Here is a page that has some nice examples:
http://blog.pythonisito.com/2012/06/using-mongodbs-new-aggregation.html

Categories