2011-07-12 77 views
2

我使用Python + MongoDB中存储一些项目被称为集合中的排名数据chartMongoDB的蟒蛇得到一个文件

{ 
    date: date1, 
    region: region1, 
    ranking: [ 
    { 
     item: bson.dbref.DBRef(db.item.find_one()), 
     price: current_price, 
     version: '1.0' 
    }, 
    { 
     item: bson.dbref.DBRef(db.item.find_another_one()), 
     price: current_price, 
     version: '1.0' 
    }, 
    .... (and the array goes on) 
    ] 
} 

现在我的问题是,我想打一个历史排名中从一个数组元素位置图表为itemA。而根据the $ positional operator,查询应该是这样的:

db.chart.find({'ranking.item': bson.dbref.DBRef('item', itemA._id)}, ['$']) 

而且$操作不起作用。

任何其他可能的解决方案?

回答

3

$位置运算符仅用于update(...)调用中,不能用它来返回数组中的位置。

但是,您可以使用field projection限制字段返回的只是那些你需要从内Python的计算数组中的位置:

db.foo.insert({ 
'date': '2011-04-01', 
'region': 'NY', 
'ranking': [ 
{ 'item': 'Coca-Cola', 'price': 1.00, 'version': 1 }, 
{ 'item': 'Diet Coke', 'price': 1.25, 'version': 1 }, 
{ 'item': 'Diet Pepsi', 'price': 1.50, 'version': 1 }, 
]}) 

db.foo.insert({ 
'date': '2011-05-01', 
'region': 'NY', 
'ranking': [ 
{ 'item': 'Diet Coke', 'price': 1.25, 'version': 1 }, 
{ 'item': 'Coca-Cola', 'price': 1.00, 'version': 1 }, 
{ 'item': 'Diet Pepsi', 'price': 1.50, 'version': 1 }, 
]}) 

db.foo.insert({ 
'date': '2011-06-01', 
'region': 'NY', 
'ranking': [ 
{ 'item': 'Coca-Cola', 'price': 1.00, 'version': 1 }, 
{ 'item': 'Diet Pepsi', 'price': 1.50, 'version': 1 }, 
{ 'item': 'Diet Coke', 'price': 1.25, 'version': 1 }, 
]}) 

def position_of(item, ranking): 
    for i, candidate in enumerate(ranking): 
      if candidate['item'] == item: 
        return i 
    return None 

print [position_of('Diet Coke', x['ranking']) 
     for x in db.foo.find({'ranking.item': 'Diet Coke'}, ['ranking.item'])] 

# prints [1, 0, 2] 

在这(诚然平凡)例如,只返回一个子集的领域可能没有多大益处;但是,如果您的文档特别大,则可能会提高性能。

+0

谢谢dcrosta。你的回答给了我一个想法:我可以使用MongoDB map-reduce直接在mongodb服务器中找到位置:D – est