有没有一种方法可以在MongoDB中使用聚合管道搜索嵌入式数组



我需要搜索categories字段中的所有数组,以确定产品是否属于"T恤"类别,是否有方法搜索category字段内的所有数组?

如有任何帮助,我们将不胜感激。

以下是我迄今为止尝试过的

// Aggregate Pipeline
db.products.aggregate([
{$group :
{_id :
{productID : '$productID', productTitle : '$productTitle ', categories: '$categories'
}
}
},
{$project :
{
category_tshirts : {$in : ['T-Shirts', '$_id.categories']}
}
}
]);

以下是其中一个文档的示例:

// Example document
{
"productID" : "B000072SJ2",
"productTitle" : "Loosegear Short Sleeve",
"categories" : [ 
[ 
"Sports & Outdoors", 
"Clothing", 
"Men", 
"Shirts", 
"T-Shirts"
], 
[ 
"Clothing, Shoes & Jewelry", 
"Men", 
"Clothing", 
"Shirts"
], 
[ 
"Clothing, Shoes & Jewelry", 
"Men", 
"Big & Tall"
]
]
}

当然。您可以使用展开运算符来消除嵌套数组。

此运算符允许您拥有与所选数组中的项目一样多的单独文档。例如,拥有以下文档:

{
"productID" : "B00006I551",
"productTitle" : "CASIO F91W-1 Casual Sport Watch",
"categories" : [ 
[ 
"Sports & Outdoors", 
"Accessories", 
"Sport Watches"
], 
[ 
"Clothing, Shoes & Jewelry", 
"Sport Watches"
], 
[ 
"Clothing, Shoes & Jewelry", 
"Men"
]
]
}

如果在categories字段上使用展开:

db.products.aggregate( [ { $unwind : "$categories" } ] )

你会得到3个几乎相似的文档,其中只有类别不同(顶层数组中每个项目一个文档(:

{
"productID" : "B00006I551",
"productTitle" : "CASIO F91W-1 Casual Sport Watch",
"categories" : [ 
"Sports & Outdoors", 
"Accessories", 
"Sport Watches"
]
},
{
"productID" : "B00006I551",
"productTitle" : "CASIO F91W-1 Casual Sport Watch",
"categories" : [ 
"Clothing, Shoes & Jewelry", 
"Sport Watches"
]
},
{
"productID" : "B00006I551",
"productTitle" : "CASIO F91W-1 Casual Sport Watch",
"categories" : [ 
"Clothing, Shoes & Jewelry", 
"Men"
]
}

现在您可以使用$in运算符或其他方式通过categories进行查询和筛选。

最新更新