我需要搜索类别字段中的所有数组以查找产品是否属于“T 恤”类别,有没有办法搜索类别字段中的所有数组?
任何帮助将不胜感激。
这是我迄今为止尝试过的
// 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"
]
]
}
当然。您可以使用unwind运算符来摆脱嵌套数组。
此运算符允许您拥有与所选数组中的项目一样多的单独文档。例如,有这个文件:
{
"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 个几乎相似的文档,其中只有类别不同(顶级数组中的每个项目有 1 个文档):
{
"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
.
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句