Python pymongo-如何为字段以及其他查询参数设置不同的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12879781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pymongo- How can I have distinct values for a field along with other query parameters
提问by Sushant Gupta
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:
我正在使用 pymongo 并希望为字段设置不同的值,以便我还可以传递其他查询参数。例如,我有以下条目:
{
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.
所以我想在电影类别下拥有所有不同的标签。任何人都可以指导我如何使用 pymongo 实现这一目标。在 mongo javascript shell 中,我发出了 db.mycoll.distinct('tags', {category: "movie"}) 并且它工作得很好。但是当我在 pymongo 中做同样的事情时,它会引发错误。我猜它在 pymongo 中不受支持。任何想法如何才能实现这样的任务。
采纳答案by JohnnyHK
You have to make the distinctcall on the cursorreturned from a findinstead of on the collection:
您必须对从 a而不是集合返回的游标进行distinct调用:find
tags = db.mycoll.find({"category": "movie"}).distinct("tags")
回答by Graham Russell
pymongo (since v1.1.1) supports collection.distinct('key')
pymongo(自 v1.1.1 起)支持 collection.distinct('key')

