如何在单个mongoDB查询中两次使用$ match运算符?

时间:2019-10-25 12:46:38

标签: mongodb mongoose

我有两个模型:

const ClientRequest = new mongoose.Schema({
   sourceLanguage: {
        type: String,
        default: '',
        trim: true
    },
    type: {
        type: String,
        default: '',
        trim: true
    },
    customer: {
        type: Schema.Types.ObjectId, ref: 'Client'
    }
}

const Client = new mongoose.Schema({
    name: {
        type: String,
        default: '',
        trim: true
    },
    web: {
        type: String,
        default: '',
        trim: true
    },
    country: {
        type: String,
        default: '',
        trim: true
    }
}

我需要找到所有由requestssourceLanguage过滤的name。 我正在使用此查询:

const requests = await ClientRequest.aggregate([
            {$match: {
                "sourceLanguage.symbol": "EN-GB"}
            },
            {
                $lookup: {
                    from: "clients",
                    localField: "customer",
                    foreignField: "_id",
                    as: "clients"
                }
            },
            {
                $match: {
                    "clients.name": filters.clientFilter,
                }
            }
        ])

但是它返回空数组。如果我删除$match之一,则可以使用。但是如何在单个查询中同时使用两个过滤器?

2 个答案:

答案 0 :(得分:0)

const requests = await ClientRequest.aggregate([
            {$match: {
                "sourceLanguage": "EN-GB",
                 "customer": ObjectId("5d933c4b8dd2942a17fca425")
               }
            },
            {
                $lookup: {
                    from: "clients",
                    localField: "customer",
                    foreignField: "_id",
                    as: "clients"
                }
            },

        ])

答案 1 :(得分:0)

我尝试了不同的方法,但有时会发生这种情况,最简单的方法就可以解决:

const requests = await ClientRequest.aggregate([
            {
                $lookup: {
                    from: "clients",
                    localField: "customer",
                    foreignField: "_id",
                    as: "customer" // I used the same name to replace the Id with the unwinded object
                }
            },
            {
                $match: {
                    "customer.name": filters.clientFilter,
                    "sourceLanguage.symbol": "EN-GB" // or any other filter
                }
            },
            {$unwind: "$customer"} // here I just unwind from array to an object
    ])