如果我使用 pymongo 的
find_one
来查询特定值,那么如果它不存在,我将简单地得到一个 None
但如果我使用 find
查询多个值,那么如果至少有一个,我将得到一个光标存在的值:
pymongo.MongoClient("Conn string")
db = db_client[some_db_name]
collection = db[some_collection_name]
id_name_queries = [(123,'George'),(234,'Jon'),(521,'Tfu')] # queries
clusters = collection.find({"$or": [
{"$and": [{"ID": pair[0]}, {"Name": pair[1]}]} for pair in id_name_queries
]
})
是否可以从
find
获取一个布尔列表(或其他可迭代的),其长度与id_name_queries
相同,指示每个查询是否存在于集合中?
ind = [True,False,True] # (234,'Jon') is not in the collection
您可以使用
$documents
存储所有搜索条目并启动 $lookup
进行收藏。检查[]
的查找结果是否返回找到。
db.aggregate([
{
"$documents": [
{
"ID": 123,
"Name": "George"
},
{
"ID": 234,
"Name": "Jon"
},
{
"ID": 521,
"Name": "Tfu"
}
]
},
{
"$lookup": {
"from": "collection",
"localField": "ID",
"foreignField": "ID",
"let": {
"name": "$Name"
},
"pipeline": [
{
"$match": {
"$expr": {
"$eq": [
"$$name",
"$Name"
]
}
}
},
{
"$limit": 1
}
],
"as": "searchResult"
}
},
{
"$group": {
"_id": null,
"result": {
"$push": {
$ne: [
[],
"$searchResult"
]
}
}
}
}
])
Mongo Playground for $documents
$documents
。这只是为了演示语法。