MongoDB查询与if条件形成具有空值的多个字段匹配

时间:2019-12-02 04:12:32

标签: mongodb mongodb-query aggregation-framework

我有一个json,我要尝试用多个字段过滤管道,其中某些字段也可以具有空值。 sender.client和Receiver.client可能不总是值

下面是示例json的一部分:

{"sender" : {
        "id" : "5d95", 
        "name" : "Name1", 
        "phone" : "123456",
        "client" : "spec1"
    }, 
    "receiver" : {
        "id" : "5d95683", 
        "name" : "name2", 
        "phone" : "342235", 
        "client" : "spec1"
    }
}

{"sender" : {
        "id" : "52fes", 
        "name" : "Name2", 
        "phone" : "3334321",
        "client" : "spec2"
    }, 
    "receiver" : {
        "id" : "5efse", 
        "name" : "name3", 
        "phone" : "7353344", 
        "client" : "spec1"
    }
}

我的目标是在(sender.client = spec1或receiver.client = spec1)然后显示所有字段的情况下进行过滤,即如果客户端名称匹配,则我必须显示其他字段必填字段。我一直在尝试$ project和$ match,但是match不能与$ cond一起使用,所以我选择了$ eq替代路线,但这没有帮助我过滤掉我的要求。下面是我的代码:

    { 
        "$project" : {
            "sendername" : {
                "$cond" : {
                    "if" : {
                        "$eq" : [
                            "$sender.client", 
                            "spec1"
                        ]
                    }, 
                    "then" : "$sender.name", 
                    "else" : 0.0
                }
            }, 
            "sendername1" : {
                "$cond" : {
                    "if" : {
                        "$eq" : [
                            "$receiver.client", 
                            "spec1"
                        ]
                    }, 
                    "then" : "$receiver.name", 
                    "else" : 0.0
                }
            }
        }
    }

我想用$ eq作为$ eq的开头。我该怎么做?

1 个答案:

答案 0 :(得分:1)

带有$match的{​​{1}}可以根据以下条件进行过滤:$expr

  

我的目标是在以下条件下进行过滤:(sender.client = spec1或   receive.client = spec1),然后显示所有字段,即   客户匹配,然后我必须显示其他必填字段。

您可以添加更多过滤器以匹配(sender.client = spec1 or receiver.client = spec1)字段(存在两个带有“名称”,namesender.name的字段;尚不清楚要匹配哪个字段。假设可以是任何一个)。

receiver.name

匹配过滤器为:var queryFilter = { $cond: { if: { $or: [ { $eq: [ "$sender.client", "spec1" ] }, { $eq: [ "$receiver.client", "spec1" ] } ] }, then: true, else: false } }; db.test.aggregate( [ { $match: { $expr: { $eq: [ queryFilter, true ], $or: [ { "sender.name" : "name3" }, { "receiver.name" : "name3" } ] } } } ] ) $expr: {...}

此外,您可以根据需要在$or: [...]阶段之后添加其他阶段(例如$project)。