在Python中查找具有多个条件的两个文档之间的字段

2024-05-12 16:22:53 发布

您现在位置:Python中文网/ 问答频道 /正文

   def method(class, doc): # read and fetch data from coll1 and get required fields
        id = doc['id']
        type = doc['type']
        startdate = doc['startDate']
        endDate = doc['endDate'])
        match = class.mongo_db['coll2'] # match fields in coll1 and coll2 and fetch data from coll2
        target = match.find({'id': id, 'type': type,'startDate':{'$lte': startdate},'endDate':{'$gte': endDate}})
        Data = []
        for data1 in target:
            Data.append(data1)
        if len(Data) == 1:
          ---------------
          ----------
          ----
          --
        else:
          skip

      
      
      

我需要匹配两个集合中的数据并获取所需的数据,如果从coll2获取了两个文档,那么我们需要跳过,否则继续

我在这方面取得了成功,没有出现问题:

如果Cul2有合适的“EdDATE”匹配,但在某些场景中,“EdDATE”将是00,那么我需要考虑它有20500202(如果结束数据是00),我怎样才能在蒙戈上面执行这个操作?p>

查找查询,如果“endDate”为00,则无法完成此操作

例如,如果COL1的结束日期为20210303,COL2的结束日期为00,则应将其视为

(20500202 > 20210303) 

不是

(00 > 20210303)`

`

-- source collection coll1
{
    "Id": "ID1",      
    "type": "DATA",
    "startdate": 20200101,
    "endDate": 20200301
}



-- collection coll2 which to match from coll1 ex_1
{
    "Id": "ID1",
    "type": "DATA",
    "startdate": 20200101,
    "endDate": 00,
    "documentId": "DSC0001",
    "documentDesc": "Value document"
}

匹配id、类型、起始日期<;(coll1开始日期),结束日期>;(第1列结束日期)

<如果COL2的结束日期为0,则我们需要考虑它为

(20500202 > 20210301)

不是

(00 > 20210303) 

因此,coll2需要的期望输出是

{
    "startdate": 20200101,
    "endDate": 0,
    "documentId": "DSC0001",
    "documentDesc": "Value document"
}

--要与coll1 ex_2匹配的coll2集合

{
    "Id": "ID1",
    "type": "DATA",
    "startdate": 20200101,
    "endDate": 20200401,
    "documentId": "DSC0001",
    "documentDesc": "Value document"
}
<>如果COL2的结束日期是适当格式,我们可以直接将其视为

20200401>20210303

因此,coll2需要的期望输出是

{
    "startdate": 20200101,
    "endDate": 0,
    "documentId": "DSC0001",
    "documentDesc": "Value document"
}

请建议我如何做到这一点

提前谢谢


Tags: andfromiddocvaluetypematchdocument
1条回答
网友
1楼 · 发布于 2024-05-12 16:22:53

您所寻找的只有在MongoDB聚合中才可能实现

如果我的理解是正确的,下面的代码就是您正在寻找的

target = match.aggregate([
  {
    "$match": {  # <  Put all your conditions except for `endDate`
      'id': id, 
      'type': type,
      'startDate':{
        '$lte': startdate
      }
    },
  },
  {
    "$project": {  # <  Keys you want to be projected from `coll2`
      "documentId": 1,
      "documentDesc": 1,
      "startdate": 1,
      "endDate": {
        "$cond": {
          "if": {
            "$in": [
              "$endDate",
              [  #  <  Add all your exceptions here
                0,
                "00",
              ]
            ]
          },
          "then": 20500202,
          "else": "$endDate",
        }
      }
    },
  },
  {
    "$match": {  # <  Add your `endDate` condition here
      "endDate": {
        "$gte": endDate,
      }
    },
  },
])

相关问题 更多 >