通过索引获取数组的不同聚合元素

时间:2015-08-20 14:12:24

标签: python mongodb mongodb-query pymongo pymongo-3.x

client = MongoClient()
db = client['test']
connection = db['test']
conn.insert({"tags": ["first_1", "second_1"]})
conn.insert({"tags": ["first_2", "second_1"]})
conn.insert({"tags": ["first_3", "second_2"]})
print conn.distinct("tags")

我得到了输出:

[u'first_1', u'second_1', u'first_2', u'first_3', u'second_2']

如何仅使用数组的第二个元素执行此操作?我需要这样的东西:

[u'second_1', u'second_2']

1 个答案:

答案 0 :(得分:0)

根据docs $elemMatch$slice$是投影数组部分的唯一方法。将来我们可以在$slice中获得aggregate功能,有关详细信息,请参阅this answer。但是现在我们没有直接的方法只使用mongo查询 工作代码:

position = 1
field = "tags"
# see https://stackoverflow.com/a/15798087/4249707
# for "not_existent_field" explanation
results = conn.find(
  {}, {field:{"$slice": [position,1]}, "_id": 0, "not_existent_field": 1}
)
distinct_results = {d[field][0] for d in results if field in d and d[field]}
相关问题