通过索引获取数组的不同聚合元素
Getting a distinct aggregation elements of array by index
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']
根据docs $elemMatch
, $slice
, and $
are the only way to project portions of an array. In the future we can get $slice
functionality in aggregate
, see this answer了解详情。但是现在我们没有直接的方法来只用 mongo 查询。
工作代码:
position = 1
field = "tags"
# see
# 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]}
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']
根据docs $elemMatch
, $slice
, and $
are the only way to project portions of an array. In the future we can get $slice
functionality in aggregate
, see this answer了解详情。但是现在我们没有直接的方法来只用 mongo 查询。
工作代码:
position = 1
field = "tags"
# see
# 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]}