【发布时间】:2019-10-11 18:30:29
【问题描述】:
我有这个聚合管道:
aggregate.lookup({
from: 'tags',
localField: 'tags',
foreignField: '_id',
as: 'tags'
});
aggregate.match({
productType: 'product',
available: true,
categories: {
$elemMatch: {
url: '/category/test'
}
}
});
aggregate.facet({
products: [
{ $sort: { [order]: sort } },
{ $skip: skip },
{ $limit: pageSize },
{
$project: {
_id: 1,
images: 1,
onSale: 1,
price: 1,
quantity: 1,
slug: 1,
sale: 1,
sku: 1,
status: 1,
title: 1,
brand: 1,
tags: 1
}
}
],
tags: [
{ $unwind: '$tags' },
{
$group: {
_id: {
name: '$name.label',
slug: '$slug'
},
count: {
$sum: 1
}
}
}
],
range: [
{
$bucketAuto: {
groupBy: '$price',
buckets: 1,
output: {
min: { $min: '$price' },
max: { $max: '$price' }
}
}
}
],
total: [{ $group: { _id: null, count: { $sum: 1 } } }]
});
aggregate.addFields({
total: {
$arrayElemAt: ['$total', 0]
}
});
aggregate.addFields({
range: {
$arrayElemAt: ['$range', 0]
}
});
每个产品都有自己的标签,我不知道怎么做:
- 获取仅属于匹配产品的标签,并从
$facet返回一个包含 的数组
tags: [{name: 'tag1', slug: 'slug1', count: 10}, {name: 'tag2', slug: 'slug2', count: 5} ]
count: 10 是带有标签的产品。
现在它返回在数据库中找到的所有标签。
2。为什么range 属性会返回这样的对象:
"range": {
"_id": {
"min": 5.9,
"max": 47
},
"min": 5.9,
"max": 47
}
不是这样,因为我在$bucketAuto 中提供了一个output 对象:
"range": {
"min": 5.9,
"max": 47
}
从 2 开始,这是 $bucketAuto 的正常 mongodb 行为。
【问题讨论】:
标签: javascript node.js mongodb mongoose