iobelix
iobelix

Reputation: 1225

Mongo projection result as an array of selected items

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

Answers (2)

Sede
Sede

Reputation: 61253

_ids are unique across the collection, thus you can use distinct here.

collection.distinct('_id', {'grocerylist' : cheddar})

Upvotes: 1

alecxe
alecxe

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

Related Questions