0
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")

I got as output:

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

How can I do this operation only with second elements of array? I need something like:

[u'second_1', u'second_2']
El Ruso
  • 14,745
  • 4
  • 31
  • 54

1 Answers1

0

According to 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 for details. But now we have no straight way to do it with only mongo query.
Working code:

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]}
Community
  • 1
  • 1
El Ruso
  • 14,745
  • 4
  • 31
  • 54