node.js - Mongoose聚合,当产品匹配时找到产品的祖先
问题描述
抱歉标题不好,找不到更好的标题。
我有一个父母Product
有一个ancestors
空的数组。
我也有ancestors
包含 parent 的Products _id
, calledvariants
以及ancestors
包含 parent 和 variant 的_id
Products options
。所有产品都在同一个文档中,没有参考。
父产品
{
productType: 'simple'
ancestors: [],
title: "Test Title",
_id: "1"
}
变体产品
{
productType: 'variant'
ancestors: ["1"],
title: "Test Variant",
_id: "2"
}
期权产品
{
productType: 'option'
ancestors: ["1", "2"],
title: "Test Variant",
_id: "3"
}
当我搜索产品时,我想在搜索结果中包含所有variants
和options
,例如:
products: [{
_id: "1",
variants: [{...}],
options: [{...}]
},
...
]
搜索端点
Product.aggregate([
{$match: {productType: 'simple'}},
{$match: {$or: [{sku: {$regex: new RegExp(makeComp(value), 'i')}}, {title: {$regex: new RegExp(makeComp(value), 'i')}}]}},
{
$project: {
_id : 1,
title : 1,
productType: 1,
ancestors: 1
}
},
], (err, result) => {
console.log(err);
console.log(result);
});
之后我尝试了很多东西,$project
但没有运气。
我必须制作一个新的find
还是aggregate
在产品匹配之后或者有一种方法可以获取一个里面的所有祖先aggregate
?
解决方案
你可以简单地find
做$or
db.products.find({$expr : {
$or : [
{"_id":1},
{"productType" : "variant", "ancestors" : 1},
{"productType" : "option", "ancestors" : 1}
]
}})
与聚合相同
db.products.aggregate([
{$match: {$expr : {
$or : [
{"_id":1},
{"productType" : "variant", "ancestors" : 1},
{"productType" : "option", "ancestors" : 1}
]
}}}
])
编辑-1
得到$lookup
结果
db.products.aggregate([
{$match: {"_id":"1"}},
{$lookup: {
from: "products",
let: {id : "$_id", productType: "$productType"},
pipeline:[{$match: {$expr: {$and: [{$in: ["$$id","$ancestors"]}, {$eq: ["$productType" ,"variant"]}]}}}],
as: "variants"
}},
{$lookup: {
from: "products",
let: {id : "$_id", productType: "$productType"},
pipeline:[{$match: {$expr: {$and: [{$in: ["$$id","$ancestors"]}, {$eq: ["$productType" ,"option"]}]}}}],
as: "options"
}}
]).pretty()
编辑-2
和$match
_ $group
_$project
db.products.aggregate([
{$match: {$expr : {
$or : [
{"_id":1},
{"productType" : "variant", "ancestors" : 1},
{"productType" : "option", "ancestors" : 1}
]
}}},
{$group: {_id: "$productType", docs : {$push : "$$ROOT"}}},
{$group: {_id: null, docs : {$push : "$docs"}}},
{$project: {
simple: {$arrayElemAt:[{$filter: {input : "$docs", as: "d", cond : {$in: ["simple", "$$d.productType"]}}},0]},
variant: {$arrayElemAt:[{$filter: {input : "$docs", as: "d", cond : {$in: ["variant", "$$d.productType"]}}},0]},
option: {$arrayElemAt:[{$filter: {input : "$docs", as: "d", cond : {$in: ["option", "$$d.productType"]}}},0]}
}}
]).pretty()
推荐阅读
- html - 如何使用 Angular 一起使用 ng-content 和 ng-switch 投影内容?
- python - 在按钮按下 kivy 时刷新小部件
- python - 合并2个不同长度的不同DataFrame
- php - 会话开始期间出错;请检查您的 PHP 和/或网络服务器日志文件并配置
- python - 是否有任何方法可以在不指定边界框的情况下分割此图像上的珠子?
- django - ezhc heatmap.build 需要 pandas.core.index 但它是 Pandas.core.index 已弃用
- python - 将 JSON 解析为对象字典
- python - 制作类似于 MATLAB 的 Python 2D 掩码数组
- javascript - 我如何在 discord.js 中访问 [[Entries]]
- python - ReportRequest 不像 Telegram Api