【问题标题】:Python MongoDB query to get list of documents where '_id' != idPython MongoDB查询以获取'_id'!= id的文档列表
【发布时间】:2021-09-09 09:00:46
【问题描述】:

我在集合中有多个文档。文档包含_idtransaction_id。在大多数文档中,_idtransaction_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

   
    

上述方法的问题在于,例如,我的交易列表为[12345, 67890]。因此,对于 transaction_id [12345]trans['_id'] 匹配,so found 变为 False,但对于另一个 trans['_id'],它变为 True,所以这种方法是不正确的。谁能建议一个查询,该查询可以列出_idtransaction_id 不匹配的所有文档。请帮忙。谢谢

【问题讨论】:

    标签: python-3.x mongodb pymongo


    【解决方案1】:

    您可以在查询中使用$expr 聚合表达式运算符和$ne 运算符,以使用$in 在提供的ID 列表中选择不匹配的文档及其transaction_id

    all_trans_doc_list = tc_coll.find({ 
      'transaction_id': { '$in': transaction_list },
      '$expr': { '$ne': ['$transaction_id', '$_id'] } 
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      相关资源
      最近更新 更多