$lookup 结果中的 $match [英] $match in $lookup result

查看:69
本文介绍了$lookup 结果中的 $match的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个 mongo 代码:

I have next mongo code:

db.users.aggregate([
    { 
        $match: { 
            $and: [
                { UserName: { $eq: 'administrator' } }, 
                { 'Company.CompanyName': { $eq: 'test' } }
            ]                   
        } 
    },
    { 
        $lookup: { 
            from: "companies", 
            localField: "CompanyID", 
            foreignField: "CompanyID", 
            as: "Company" 
        } 
    },
])

代码的 $lookup 部分运行良好.我得到了下一个结果:

The $lookup part of the code working great. I got next result:

但是如果我将 $match 添加到代码中,它不会带来任何东西.

But if I add $match to the code, it brings nothing.

我发现问题出在第二个匹配项中:{ 'Company.CompanyName': { $eq: 'test' } },但我无法意识到它有什么问题.有什么想法吗?

I found that the problem is in the second match: { 'Company.CompanyName': { $eq: 'test' } }, but I can not realize what is wrong with it. Any ideas?

更新:

我也在 $lookup 结果上尝试了 $unwind,但没有成功:

I had also tried $unwind on the $lookup result, but no luck:

db.users.aggregate([
    { 
        $match: { 
            $and: [
                { UserName: { $eq: 'administrator' } }, 
                { 'Company.CompanyName': { $eq: 'edt5' } }
            ] 
        } 
    },
    {   unwind: '$Company' },
    { 
        $lookup: { 
            from: 'companies', 
            localField: 'CompanyID', 
            foreignField: 'CompanyID', 
            as: 'Company' 
        } 
    },
])

推荐答案

使用 MongoDB 3.4,您可以运行使用 $addFields 管道和一个 $filter 操作符只返回Company 数组,包含与给定条件匹配的元素.然后您可以包装 $filter 表达式与 $arrayElemAt 运算符返回单个文档,该文档实质上包含了 $unwind 通过扁平化数组来实现功能.

With MongoDB 3.4, you can run an aggregation pipeline that uses the $addFields pipeline and a $filter operator to only return the Company array with elements that match the given condition. You can then wrap the $filter expression with the $arrayElemAt operator to return a single document which in essence incorporates the $unwind functionality by flattening the array.

按照这个例子来理解上面的概念:

Follow this example to understand the above concept:

db.users.aggregate([
    { "$match": { "UserName": "administrator" } },
    { 
        "$lookup": { 
            "from": 'companies', 
            "localField": 'CompanyID', 
            "foreignField": 'CompanyID', 
            "as": 'Company' 
        } 
    },
    {
        "$addFields": {
            "Company": {
                "$arrayElemAt": [
                    {
                        "$filter": {
                            "input": "$Company",
                            "as": "comp",
                            "cond": {
                                "$eq": [ "$$comp.CompanyName", "edt5" ]
                            }
                        }
                    }, 0
                ]
            }
        }
    }
])

这篇关于$lookup 结果中的 $match的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆