如何在数组字段具有最多匹配元素的查找中匹配同一集合的文档?
我有一个带有模式的产品集合,如下所示:
{
brand: String,
category: String,
title: String,
description: String,
product_variants: [...],
tags: [{label:String},{value:String}],
}
我正在同一集合中进行查找,以添加由每种产品的相关产品组成的字段。我需要通过匹配标签数组中具有相似元素的文档来获取相关产品。到目前为止,我有以下查找管道:
{
$lookup: {
from: 'products',
let: { "tags": "$tags.label" },
pipeline: [{
$match: {'product_variants.status': {$eq: 'Active'}}
},
{
'$match': {
'$expr': {
'$in': ['$tags.label', '$$tags']
}
},
},
{
$match: { 'product_variants': {
$elemMatch: {
'variant_details': {
$elemMatch: {
'inventory': {
$elemMatch: {
quantity: {$gt:0},
}
}
}
}
}
}}
}, {
$project: {
product_variants: {
"$filter": {
"input": {
"$map": {
"input": "$product_variants",
"as": "variants",
"in": {
"variant_code": "$$variants.variant_code",
"images": {$slice: ["$$variants.images", 1]},
"slug": "$$variants.slug"
}
}
},
"as": "related_products",
"cond":{$gt: [{$size: "$$related_products.images"}, 0]}
}
}
}
}, { $limit: 3 } ],
"as": "related_products"
}
},
我尝试使用$所有操作员,但也无法正常工作。
I have a products collection with a schema as follows:
{
brand: String,
category: String,
title: String,
description: String,
product_variants: [...],
tags: [{label:String},{value:String}],
}
I am performing a lookup in the same collection to add a field consisting of related products for each product. I need to get related products by matching documents that have similar elements in the tags array. So far I have the got the following lookup pipeline:
{
$lookup: {
from: 'products',
let: { "tags": "$tags.label" },
pipeline: [{
$match: {'product_variants.status': {$eq: 'Active'}}
},
{
'$match': {
'$expr': {
'$in': ['$tags.label', '$tags']
}
},
},
{
$match: { 'product_variants': {
$elemMatch: {
'variant_details': {
$elemMatch: {
'inventory': {
$elemMatch: {
quantity: {$gt:0},
}
}
}
}
}
}}
}, {
$project: {
product_variants: {
"$filter": {
"input": {
"$map": {
"input": "$product_variants",
"as": "variants",
"in": {
"variant_code": "$variants.variant_code",
"images": {$slice: ["$variants.images", 1]},
"slug": "$variants.slug"
}
}
},
"as": "related_products",
"cond":{$gt: [{$size: "$related_products.images"}, 0]}
}
}
}
}, { $limit: 3 } ],
"as": "related_products"
}
},
I have tried using $all operator but it is not working either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论