$lookup 在 mongodb 聚合中不起作用

Posted

技术标签:

【中文标题】$lookup 在 mongodb 聚合中不起作用【英文标题】:$lookup not working when in mongodb aggregrate 【发布时间】:2021-12-01 19:21:33 【问题描述】:

我有一个问题

fromDate = '2021-10-01'
toDate = '2021-10-10'
dataType = 'location'
typeId = '60dd6d303da6c17209d5ef68'
workerType = 'Employee'

start_date = datetime.strptime(str(fromDate)+" 00:00:00", '%Y-%m-%d %H:%M:%S')
end_date = datetime.strptime(str(toDate)+" 00:00:00", '%Y-%m-%d %H:%M:%S')

if dataType == 'location':
    found_location = prodLocationCollection.find_one("_id":ObjectId(typeId))
    match_filter = 'Date':"$gte":start_date,"$lte":end_date,
                                    'Location':found_location["locationName"],
                                    'locationId':'$exists':True,
                                'workerType':workerType
                                    
elif dataType == 'user':
    match_filter = 'Date':"$gte":start_date,"$lte":end_date,
                                    'employeeId':ObjectId(typeId),
                                    'locationId':'$exists':True,
                                'workerType':workerType
                                    
    


output = list(prodAttendanceCollection.aggregate(['$match': match_filter,
                        "$group":'_id':
                                'employeeId':'$employeeId',
                                'workerId':'$workerId',
                                'workerFullName':'$workerFullName'
                                ,
                                'dailyPointsArray':
                                    '$push':
                                    'Date':'$Date',
                                    'createdAs':'$createdAs',
                                    'Points':'$shiftPoints'
                                    
                                ,
                                'total_shift_points':'$sum':'$shiftPoints',
                                'total_duration':'$sum':'$duration',
                                
                        ,
         '$lookup':
            
               'from': "users",
               'localField': "employeeId",
               'foreignField': "_id",
               'as': "userInfo"
            
    
                                                  
]))

这是输出

['_id': 'employeeId': ObjectId('60dd78184524e6c116e22a44'),
   'workerId': '1008',
   'workerFullName': 'RADHIKA GOTHIVREKAR',
  'dailyPointsArray': ['Date': datetime.datetime(2021, 10, 1, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 2, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 3, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 4, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 5, 0, 0),
    'createdAs': 'IN-TIME PUNCHED',
    'Points': 0,
   'Date': datetime.datetime(2021, 10, 6, 0, 0),
    'createdAs': 'FULL-TIME PUNCHED',
    'Points': 1,
   'Date': datetime.datetime(2021, 10, 7, 0, 0),
    'createdAs': 'FULL-TIME PUNCHED',
    'Points': 1,
   'Date': datetime.datetime(2021, 10, 8, 0, 0),
    'createdAs': 'FULL-TIME PUNCHED',
    'Points': 1,
   'Date': datetime.datetime(2021, 10, 9, 0, 0),
    'createdAs': 'FULL-TIME PUNCHED',
    'Points': 1,
   'Date': datetime.datetime(2021, 10, 10, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None],
  'total_shift_points': 4,
  'total_duration': 0,
  'userInfo': [],
 '_id': 'employeeId': ObjectId('60dd77e34524e6c116e1b27d'),
   'workerId': '1365',
   'workerFullName': 'HARISON NIKALJE',
  'dailyPointsArray': ['Date': datetime.datetime(2021, 10, 1, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 2, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 3, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 4, 0, 0),
    'createdAs': 'IN-TIME PUNCHED',
    'Points': 0,
   'Date': datetime.datetime(2021, 10, 5, 0, 0),
    'createdAs': 'IN-TIME PUNCHED',
    'Points': 0,
   'Date': datetime.datetime(2021, 10, 6, 0, 0),
    'createdAs': 'IN-TIME PUNCHED',
    'Points': 0,
   'Date': datetime.datetime(2021, 10, 7, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 8, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 9, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None,
   'Date': datetime.datetime(2021, 10, 10, 0, 0),
    'createdAs': 'ABSENT',
    'Points': None],
  'total_shift_points': 0,
  'total_duration': 0,
  'userInfo': []]

如您所见,一切正常,但查找部分返回 [] 空数组

这是考勤和用户的示例数据

出席率


    "_id": 
        "$oid": "60dd7d723fcb2eb7df248af3"
    ,
    "workerId": "2073",
    "workerFullName": "ARUN NAIR",
    "workerType": "Employee",
    "workerAadharCardNumber": "xxxxxxxxxx",
    "Date": 
        "$date": "2021-07-01T00:00:00.000Z"
    ,
    "employeeId": 
        "$oid": "60dd77c14524e6c116e1692c"
    ,
    "Location": "HEAD OFFICE 2",
    "sourceUnitType": null,
    "duration": null,
    "shiftPoints": null,
    "createdAs": "ABSENT",
    "ruleApplied": null,
    "detections": [],
    "locationId": 
        "$oid": "60dd6d303da6c17209d5ef68"
    ,
    "workerFaceRegistered": true

用户

    
    "_id": 
        "$oid": "60dd77c14524e6c116e1692c"
    ,
    "workerFirstName": "ARUN",
    "workerSurname": "NAIR",
    "workerPhoneNumber": "xxxxxxxxxx",
    "workerId": "2073",
    "locationType": "HEAD OFFICE",
    "locationName": "HEAD OFFICE 2",
    "workerDesignation": "EXECUTIVE",
    "workerDepartment": "SALES",
    "workerAadharCardNumber": "xxxxxxxxxx",
    "workerType": "Employee",
    "workerEmail": "xxxxxxxxxxxx",
    "workerStatus": "REGULAR",
    "workerUsername": "2073",
    "workerPassword": "$2b$12$wBrDRYgPbRxrLG8N9Wxs2eDxGVFauZMraosrkePnYWWpZmPE1ljY2",
    "totalLoginAttemptLeft": 3,
    "lastLocationId": 
        "$oid": "60dd6d303da6c17209d5ef68"
    ,
    "allowFencing": true,
    "workerFaceRegistered": true,
    "isActive": false

【问题讨论】:

我认为您的示例中没有给出USER._id。你能更新你的例子让我们看看吗?此外,从您的输出中,我们只能看到 _id.employeeId 而不是您在 $lookup 中使用的 employeeId。您可能希望确保使用正确的字段进行查找并且它们具有相同的数据类型(即两者都是字符串/都是 objectId) @ray 是的,当然。 数据类型对我来说看起来不错。您是否尝试在 localField 中使用 _id.employeeId 而不是employeeId? 【参考方案1】:

分组后原来的字段不存在了,所以$employeeId不存在,不会匹配任何东西。

由于employeeId在小组赛中被移动到_id.employeeId,所以在查找中使用localField: "_id.employeeId"

【讨论】:

以上是关于$lookup 在 mongodb 聚合中不起作用的主要内容,如果未能解决你的问题,请参考以下文章

Mongodb聚合$lookup $project和$match不起作用[重复]

查找聚合中的管道在 mongodb 中不起作用

在聚合管道中设置条件在 mongodb 中不起作用

mongodb 管道 $lookup 中的 $in/$eq 不起作用

MongoDB在具有附加字段的对象数组上聚合$lookup

MongoDB在具有附加字段的对象数组上聚合$lookup