简体   繁体   English

MongoDB:$lookup 后嵌套文档上的 $match

[英]MongoDB: $match on a nested document after $lookup

I need to query a collection of timecards which are linked to jobs, while jobs are linked to facilities with a specific facility ID.我需要查询与作业相关联的考勤卡集合,而作业则与具有特定设施 ID 的设施相关联。 I have the following aggregation query:我有以下聚合查询:

Timecard.aggregate([
    { $match: query }, //some query parameters set before, doesn't matter here
    {
        $lookup: {
            from: 'jobs',
            as: 'job',
            localField: 'job',
            foreignField: '_id'
        }
    },
    { $unwind: '$job' },
    {
        $lookup: {
            from: 'facilities',
            localField: 'job.facilityId'
            foreignField: '_id',
            as: 'job.facilityId'
        }
    },
    { $unwind: '$job.facilityId' },
    { $match: {'job.facilityId._id':'5cad048d95d61a002f5a9edb'}}
];)

Everything before the last $match works just fine, jobs are populated into timecards, facilities are populated into jobs.在最后一个 $match 之前的一切工作正常,工作被填充到考勤卡中,设施被填充到工作中。 But the match doesn't work for some reason.但比赛由于某种原因不起作用。 However, if I add facilityId field with但是,如果我添加 factoryId 字段

{$addFields: {facilityId: '$job.facilityId._id'}}

and change the $match to并将 $match 更改为

{$match: 'facilityId':'5cad048d95d61a002f5a9edb'}

then it works.那么它的工作原理。 The question is, is there a way to query a subdocument's field with dot notation this way?问题是,有没有办法以这种方式用点表示法查询子文档的字段?

您的最后一行可能需要是 ObjectId

{ $match: {'job.facilityId._id': ObjectId('5cad048d95d61a002f5a9edb')}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM