我使用 python + mongodb 将一些项目排名数据存储在名为 chart
的集合中
{
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)}, ['$'])
并且 $
运算符不起作用。
还有其他可能的解决方案吗?
最佳答案
$
位置运算符仅在 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]
在这个(诚然是微不足道的)示例中,仅返回字段的子集可能不会显示出太多好处;但是,如果您的文档特别大,这样做可能会提高性能。
关于python - mongodb python 从文档中的数组中获取元素位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6658842/