筛选MongoDB中的成员元素列表



所以我使用Python+Pymongo(虽然这个问题可以适用于任何语言),我在Python, emails=['email1@example.com','email2@example.com',...]中有一份电子邮件列表,我在MongoDB中有一堆文档。MongoDB中的每个文档都有一个email字段。什么是过滤Python列表的最有效(和优雅)的方法,所以当我完成它只包含在MongoDB的email字段之一存在的电子邮件?

INPUT: emails=['email1@example.com','email2@example.com',...]

OUTPUT: filteredEmails=[ <sublist of 'emails' with only elements present in MongoDB

我想这就是你要找的:

> db.people.insert({name:"Fred",email:"fred@email.com"})
> db.people.insert({name:"Derf",email:"derf@email.com"})
> db.people.insert({name:"Bob",email:"bob@email.com"})
>
>
> emails = ["derf@email.com", "bob@email.com"]
[ "derf@email.com", "bob@email.com" ]
> db.people.find({email:{$in: emails}})
{ "_id" : ObjectId("53a1f4b44336adbf6340356a"), "name" : "Derf", "email" : "derf@email.com" }
{ "_id" : ObjectId("53a1f4bb4336adbf6340356b"), "name" : "Bob", "email" : "bob@email.com" }

简单地使用.find()$in运算符来查找电子邮件列表中所有电子邮件的文档。

假设email字段已被索引,只需查找每个值。这应该够快了。

common_emails = [ email for email in emails if coll.find_one({ 'email': email }) ]

如果集合很小,或者你不想索引email字段,在内存中做交集会更快:

db_emails = [ doc['email'] for doc in coll.find({}, projection = {'email':1, '_id':0}) if doc ]
common_emails = set(emails) & set(db_emails)

最新更新