python - mongodb python 从文档中的数组中获取元素位置

标签 python mongodb nosql

我使用 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/

相关文章:

python - jupyter 服务器 : not started, vs 代码中没有内核

python - matplotlib中从右到左的水平条形图

mongodb - 如何将引用的可打印解码器实现为阅读电子邮件正文?

node.js - 如何返回与隐私值相关的特定对象值?

python - XSL转换,请求子节点数据

Python datetime 到 microtime

MongoDB,forEach 和 Promise : How to know when a forEach loop is done?

mongodb - 如何在 mongodb 的 BinData 字段上通过部分二进制查找?

php - 在 Doctrine 上优化 MongoDB 查询

nosql - Graph DB 与社交网络应用程序的 Azure 表存储