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']

1 Answer 1

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]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.