我遇到了一大堆代码,一个旨在在mongo DB中找到缺失值的函数,代码看起来:
def missing(config, list_of_clients):
collection = connect_2_mongo_db("collection", urls[config], users[config], pwd[config])
missing_clients = []
for c in list_of_clients:
cursor = collection.find({ "ClientID" : c }, {"ClientID" : 1, "_id" : 0 } )
if len(list(cursor)) == 0:
missing_clients.append(c)
return missing_clients
当然这是非常昂贵的,有没有更好的方法来使用mongo查询一次获取所有缺少的值? list_of_clients看起来像list_of_clients = [1,2,3],文档看起来像
{
"ClientID": 2,
"Address" : "blah blah blah"
...
}
{
"ClientID": 3,
"Address" : "blah blah blah"
...
}
我想知道哪些客户不在基地。在这种情况下1
答案 0 :(得分:1)
您可以使用运算符$in
和客户ID列表
result = coll.find({
"clientID": { "$in": list_of_clients }
})
将结果放入列表
existing_clients=[]
for c in result:
existing_clients.append(c["clientID"])
并最终获得这些列表差异所缺少的ID
missing_ids = list(set(list_of_clients)-set(existing_clients))
<小时/> 同样的事情,用列表理解写的
def missing(list_of_clients):
e = [c["clientID"] for c in coll.find({"clientID":{"$in":list_of_clients}})]
return list(set(list_of_clients)-set(e))
答案 1 :(得分:0)
没有mongo实例试过这个。你可以尝试一下
def missing(config, list_of_clients):
collection = connect_2_mongo_db("collection", urls[config], users[config], pwd[config])
missing=[]
for c in list_of_clients:
cursor = collection.find({ClientID: {$nin: c}});
missing.append(cursor)
return missing