从排名基础上的聚合查询数据mongodb python

时间:2018-01-20 10:57:22

标签: python mongodb aggregation-framework

我正在尝试根据主题标记查询排名数据

这是我的文件

{
    "_id" : ObjectId("5a620a1b0856ed736ffe1163"),
    "name" : "saif",
    "science" : 25,
    "roll no" : 10,
    "maths" : 89,
    "class" : 1,
    "history" : 14
}
{
    "_id" : ObjectId("5a620a3f0856ed78ff23a5f7"),
    "name" : "john",
    "science" : 62,
    "roll no" : 18,
    "maths" : 69,
    "class" : 1,
    "history" : 28
}
{
    "_id" : ObjectId("5a620a630856ed7ec14b8cd9"),
    "name" : "peter",
    "science" : 22,
    "roll no" : 8,
    "maths" : 59,
    "class" : 1,
    "history" : 58
}
{
    "_id" : ObjectId("5a620aa90856ed0ce5c4432d"),
    "name" : "zarar",
    "science" : 22,
    "roll no" : 15,
    "maths" : 29,
    "class" : 4,
    "history" : 58
}
{
    "_id" : ObjectId("5a620ac10856ed10b8f5af4a"),
    "name" : "abir",
    "science" : 22,
    "roll no" : 24,
    "maths" : 23,
    "class" : 9,
    "history" : 58
}

我可以使用此代码获取排名数据列表

from pymongo import MongoClient # import mongo client to connect  
from bson.son import SON
import pprint  
# Creating instance of mongoclient  
client = MongoClient()  
# Creating database  
db = client.school  

# Creating document  
candidates = db.candidates  
# Inserting data 

mathpipeline=[
  { "$sort": { "class" : 1,"maths" : -1} },   
   { "$group": {
    "_id": "$class",

    "items": { "$push": "$$ROOT" }
  }},
  { "$unwind": { "path": "$items", "includeArrayIndex": "items.rank", } },

  { "$project": { 
    "_id": 0, 
    "name":"$items.name",
    "class": "$items.class", 
    "maths": "$items.maths",
    "rank": { "$add": [ "$items.rank",1] } 
  }},
  { "$sort": { "class" : 1,"maths" : -1}}
]

# Fetching data  
data=list(db.candidates.aggregate(mathpipeline) 

pprint.pprint(data)

在输出中,我可以按排名获得列表

[{u'class': 1, u'maths': 89, u'name': u'saif', u'rank': 1L},
 {u'class': 1, u'maths': 69, u'name': u'john', u'rank': 2L},
 {u'class': 1, u'maths': 59, u'name': u'peter', u'rank': 3L},
 {u'class': 4, u'maths': 29, u'name': u'zarar', u'rank': 1L},
 {u'class': 9, u'maths': 23, u'name': u'abir', u'rank': 1L}]

但是如果我想根据卷号和类只查询一个用户数据呢?

我尝试使用data=list(db.candidates.aggregate(mathpipeline).find_one({'class':1,'roll no':10},{'name':1,'maths':1 })),但没有运气。非常感谢

我的预期输出是单字典,如果我想查询来自卷号和类的数据,例如,如果约翰卷数为18且类为1

所以我的输出就像

{u'class': 1, u'maths': 69, u'name': u'john', u'rank': 2L}

关心赛义夫

0 个答案:

没有答案