如何在单个mongoDB查询中使用$match运算符两次?
我有两种型号:如何在单个mongoDB查询中使用$match运算符两次?,mongodb,mongoose,Mongodb,Mongoose,我有两种型号: const ClientRequest = new mongoose.Schema({ sourceLanguage: { type: String, default: '', trim: true }, type: { type: String, default: '', trim: true }, customer: { typ
const ClientRequest = new mongoose.Schema({
sourceLanguage: {
type: String,
default: '',
trim: true
},
type: {
type: String,
default: '',
trim: true
},
customer: {
type: Schema.Types.ObjectId, ref: 'Client'
}
}
及
我需要找到所有通过sourceLanguage
和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
,它会工作。但是,如何在一个查询中同时使用这两个过滤器呢?我尝试了不同的方法,但有时会出现这种情况,最简单的方法是:
const requests = await ClientRequest.aggregate([
{$match: {
"sourceLanguage": "EN-GB",
"customer": ObjectId("5d933c4b8dd2942a17fca425")
}
},
{
$lookup: {
from: "clients",
localField: "customer",
foreignField: "_id",
as: "clients"
}
},
])
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
])
我没有客户的id
。我将name
作为customerYes的过滤器,这就是为什么我想找到一种通过name
过滤的方法,该方法是使用其他过滤器在单个查询中对另一个模型的引用。只需使用此查询并以简单的方式填充和获取客户端名称
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
])