Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

python - pymongo- How can I have distinct values for a field along with other query parameters

I am using pymongo and want to have distinct values for a field such that I can also pass other query parameters. For example, I have entries like:

{
   id = "my_id1"
   tags: [tag1, tag2, tag3],
   category: "movie",
}
{
   id = "my_id2"
   tags: [tag3, tag6, tag9],
   category: "tv",
}
{
   id = "my_id3"
   tags: [tag2, tag6, tag8],
   category: "movie",
}

So I want to have all distinct tags under movie category. Can anyone please guide how can I achive this using pymongo. In mongo javascript shell, I issued db.mycoll.distinct('tags', {category: "movie"}) and it worked just fine. But when I do the same in pymongo it raises error. I guess it is not supported in pymongo. Any idea though how can such a task be achieved.

question from:https://stackoverflow.com/questions/12879781/pymongo-how-can-i-have-distinct-values-for-a-field-along-with-other-query-param

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to make the distinct call on the cursor returned from a find instead of on the collection:

tags = db.mycoll.find({"category": "movie"}).distinct("tags")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...