Python MongoDB 查询以获取 '_id' != id 的文档列表
Python MongoDB query to get list of documents where '_id' != id
我在 collection 中有多个文档。文档包含 _id
和 transaction_id
。在大多数文档中,_id
与 transaction_id
相同。我必须检查是否有特定 transaction_id
的文档不匹配 _id
。为此,我使用下面的应用程序
all_trans_doc_list = list(tc_coll.find({})) # Getting all docs from collection
for transaction_id in transaction_list:
found = False
for trans in all_trans_doc_list:
if str(trans['_id']) == str(transaction_id ):
found = False
else:
found = True
上述方法的问题在于,对于 ex,我的交易列表为 [12345, 67890]
。所以对于 transaction_id [12345]
和 trans['_id']
匹配,so found 变为 False 但对于另一个 trans['_id']
它变为 True,所以这种方法是不正确的。任何人都可以提出一个查询,该查询可以列出 _id
和 transaction_id
不匹配的所有文档。请帮忙。谢谢
您可以在查询中使用 $expr
聚合表达式运算符和 $ne
运算符来 select 不匹配的文档及其在提供的 ID 列表中的 transaction_id
使用 $in
,
all_trans_doc_list = tc_coll.find({
'transaction_id': { '$in': transaction_list },
'$expr': { '$ne': ['$transaction_id', '$_id'] }
})
我在 collection 中有多个文档。文档包含 _id
和 transaction_id
。在大多数文档中,_id
与 transaction_id
相同。我必须检查是否有特定 transaction_id
的文档不匹配 _id
。为此,我使用下面的应用程序
all_trans_doc_list = list(tc_coll.find({})) # Getting all docs from collection
for transaction_id in transaction_list:
found = False
for trans in all_trans_doc_list:
if str(trans['_id']) == str(transaction_id ):
found = False
else:
found = True
上述方法的问题在于,对于 ex,我的交易列表为 [12345, 67890]
。所以对于 transaction_id [12345]
和 trans['_id']
匹配,so found 变为 False 但对于另一个 trans['_id']
它变为 True,所以这种方法是不正确的。任何人都可以提出一个查询,该查询可以列出 _id
和 transaction_id
不匹配的所有文档。请帮忙。谢谢
您可以在查询中使用 $expr
聚合表达式运算符和 $ne
运算符来 select 不匹配的文档及其在提供的 ID 列表中的 transaction_id
使用 $in
,
all_trans_doc_list = tc_coll.find({
'transaction_id': { '$in': transaction_list },
'$expr': { '$ne': ['$transaction_id', '$_id'] }
})