这是一个集合.我以为你有quotations
个Collection 和customers
个Collection .
$lookup
customers
集合,并将每个Quotation.customer
值与Customer._id
值进行匹配.
customer.firstName
customer.firstName
02.
$unwind
新的customer
字段,因为$lookup
总是返回一个array.
const quotations = await Quotation.aggregate([
{
$lookup: {
"from": "customers",
"localField": "customer",
"foreignField": "_id",
"as": "customer"
}
},
{
$match: {
"customer.firstName": keyword
}
},
{
$unwind: "$customer"
}
])
第HERE章一个工作的例子
Edit:
为了提高效率,在上面的示例中,我将$match
级移到了$unwind
级之前,因为如果你有很多结果,$unwind
可能会很昂贵,所以通过首先使用$match
,你在最后一级中将数字减少到$unwind
.
另一种 Select 是首先搜索customers
个集合.使用返回的结果构造一个由ObjectId
组成的数组,并将这些数组传递给具有$in
的find
以查找customer
上的匹配项,如下所示:
const customers = await Customer.find({firstName: keyword});
const ids = customers.map((c) => c._id);
const quotations = await Quotation.find({
customer: {
$in: ids
}
}).populate('customer');
最后,效率最低的是搜索quotations
个集合,搜索具有customers
的populate
个集合.从返回的结果中,您可以筛选customer.firstName
个匹配项的数组,如下所示:
const docs = await Quotation.find({}).populate('customer');
const quotations = docs.filter((d) => d.customer?.firstName === keyword);