Reputation: 1225
For the given documents in the mongo
{"_id" : "joe":
grocerylist: [ "cheddar", "apple", "oranges" ]
}
{"_id" : "joanna":
grocerylist: [ "cheddar", "foobar" ]
}
{"_id" : "john":
grocerylist: [ "apple", "oranges" ]
}
If I search for user with cheddar in their list
find({"grocerylist" : cheddar}, fields={'_id' : 1})
I get
[{u'_id': u'joe'}, {u'_id': u'joanna'}]
Using Mongo, how can I get just a list of matched users, like this..
[u'joe', u'joanna']
Thanks.
Upvotes: 2
Views: 325
Reputation: 61253
_id
s are unique across the collection, thus you can use distinct
here.
collection.distinct('_id', {'grocerylist' : cheddar})
Upvotes: 1
Reputation: 474021
One option would be to use a list comprehension:
cursor = db.col.find({"grocerylist" : cheddar}, fields={'_id' : 1})
print([document['user'] for document in cursor])
Upvotes: 1