问题描述
我想创建一个过滤器体验,我从请求参数中获取过滤条件,并使用 mongo 聚合框架对数据进行过滤。请建议我一个合适的方法。
让收集的数据像
{
"material": "silver","type": "beads","shape": "round","_user": "5f9b78bf1130ca88e2e1d"
},{
"material": "mixed","type": "jewels",{
"material": "gold","shape": "other","_user": "5fda2b717112437f9c06"
},{
"material": "silver","_user": "5fda2b717112437f9c706"
},
让查询的数据为 _user 等于 5f9b78bf1130ca88e2e1d, 材料等于一组银,混合, 类型等于一组珠子、珠宝 & 形状等于 round
的数组我的查询应返回每个过滤器类别(用户、材料、形状、类型)中的后续计数。
data = {
categorizedByUser: [
{
_id: '5f9b78bf1130ca88e2e1d',count: 2
},{
_id: '5fda2b717112437f9c06',count: 0
},],categorizedByMaterial: [
{
_id: 'silver',count: 1
},{
_id: 'mixed',{
_id: 'gold',categorizedByShape: [
{
_id: 'round',{
_id: 'other',]
categorizedByType: [
{
_id: 'beads',{
_id: 'jewels',]
]
解决方法
您可以使用 $facet
对传入的数据进行分类
db.collection.aggregate([
{
$facet: {
categorizedByUser: [
{
$group: {
_id: "$_user",count: {
$sum: 1
}
}
}
],categorizedByMaterial: [
{
$group: {
_id: "$material",categorizedByShape: [
{
$group: {
_id: "$shape",categorizedByType: [
{
$group: {
_id: "$type",count: {
$sum: 1
}
}
}
]
}
}
])