【发布时间】:2020-05-30 17:32:26
【问题描述】:
我有两个如下所示的 MongoDB 集合:
Products Specials
---------- ----------
_id _id
name product_id
country zip
price percent_discount
out_of_stock
我也在使用 GraphQL,所以我编写了一个聚合管道,以这种结构返回数据:
specials {
_id
product {
_id
name
country
price
}
zip
percent_discount
out_of_stock
}
我写的这个聚合管道效果很好,看起来像这样:
let response = await Specials.aggregate([
{
$lookup: {
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'product'
}
},
{
$unwind: '$product'
},
{
$match: {
zip: zip
}
}
])
return response;
现在我正在尝试在其中添加一个过滤器。过滤器应与产品集合中的名称或国家/地区匹配,最好使用正则表达式。所以我试着写这样的东西,但它产生了超过 8000 个结果,而应该只有 2-3 个:
let response = await Specials.aggregate([
{
$match: { zip: zip }
},
{
$lookup: {
from: "products",
let: { product_id: "$product_id" },
pipeline: [
{
$match: {
$expr: {
$and: [
{
_id: "$$product_id"
},
{
$or: [
{
name: filter
},
{
country: filter
}
]
}
]
}
}
}
],
as: "product"
}
},
{
$unwind: "$product"
}
])
【问题讨论】:
-
关于您在这里缺少的基本内容是您已经创建了局部变量
product_id,但您没有将它与products集合中的_id匹配!!不需要吗? -
试试这个 ::
{ $match: { $expr: { $eq: ["$$product_id", "$_id"], { $or: [ { $eq: ["$name", ''], }, { $eq: ["$country", ''], }, ] } } } -
无权访问lappy,将'$eq'和'$or'都包裹在'$and'中..
-
啊好吧,效果很好!这是完全有道理的。如果您想用正确的管道回答问题,我可以接受,或者我可以自己写答案并@你
-
除了你给我的解决方案正则表达式效果很好,谢谢!
标签: mongodb aggregation-framework