我有一个使用聚合的工作猫鼬查询,其中我根据对象数组中的值过滤数据,并且由于需求的变化而陷入麻烦。
这就是我的数据在MongoDB中的样子(它已经填充了虚拟数据)
{
"_id" : ObjectId("5ef44528af5a1a2a641cd52b"),
"active" : true,
"name" : "CompanyA",
"contacts" : [
{
"secondary_emails" : [],
"_id" : ObjectId("5f19727495f4da29403923e3"),
"email" : "contact@gmail.com",
"designation" : "VP Cloud & Security",
"address" : "",
"name" : "Ron"
}
],
"services" : [
{
"active" : true,
"_id" : ObjectId("5ef44528af5a1a2a641cd52d"),
"name" : "Company Management",
"title" : "Company Helpline",
"description" : "Offering voice, meetings, collaboration and contact center all on one cloud platform.",
"categories" : [
"SD-WAN",
"Security and Compliance"
],
"sub_categories" : [
"Solution"
],
},
{
"active" : true,
"_id" : ObjectId("5ef44528af5a1a2a641cd52c"),
"name" : "Company HR",
"title" : "Human Resources",
"description" : "Offering HR Services to all",
"categories" : [
"HR", "Company"
],
"sub_categories" : [
"Solution"
],
}
]}
目标:筛选服务基于用户提供的类别(假设它的"SD-WAN"),在类别是单数之前,现在它是一个值数组,因为一个服务可以属于多个类别。
以前的解决方案我的猫鼬查询(用于单数类别值)如下所示:
db.Collection("suppliers").aggregate([
{
$project: {
services: {
$filter: {
input: "$services",
as: "services",
cond: { $eq: ["$$services.category", "SD-WAN" ] },
},
},
},
},
{ $match: { services: { $exists: true, $not: { $size: 0 } } } },
]);
我很难在SD-WAN
中搜索$$services.categories
,这是一个值数组。是否有任何方法更新上述查询,以便使用services.categories
管道操作符或其他解决方案在$eq
数组中搜索值。
预期结果
"_id" : ObjectId("5ef44528af5a1a2a641cd52b"),
"services" : [
{
"active" : true,
"_id" : ObjectId("5ef44528af5a1a2a641cd52d"),
"name" : "Company Management",
"title" : "Company Helpline",
"description" : "Offering voice, meetings, collaboration and contact center all on one cloud platform.",
"categories" : [
"SD-WAN",
"Security and Compliance"
],
"sub_categories" : [
"Solution"
],
}
]
如果有人能帮我解决这个问题,我会很感激的。如果需要更多的信息,请询问。谢谢。
发布于 2020-07-30 08:01:03
这就是你要找的。
[
{
$unwind: "$services"
},
{
$match: {
"services.categories": "SD-WAN"
}
},
{
$group: {
_id: "$_id",
active: {
$first: "$active"
},
name: {
$first: "$name"
},
contacts: {
$first: "$contacts"
},
services: {
$addToSet: "$services"
}
}
}
]
$unwind
将数组扁平化$match
进行过滤$group
对其进行分组。我们只对服务进行扁平处理。这就是我使用$addToSet
的原因
工作蒙戈游乐场
发布于 2020-07-30 08:20:46
以下是另一种不使用聚合游乐场链接的方法:https://mongoplayground.net/p/jmLghGBXb7f
db.collection.find({
"services": {
$elemMatch: {
categories: {
$regex: "SD-WAN",
$options: "i"
}
}
}
},
{
"services": {
$elemMatch: {
categories: {
$regex: "SD-WAN",
$options: "i"
}
}
}
})
产出:
[
{
"_id": ObjectId("5ef44528af5a1a2a641cd52b"),
"services": [
{
"_id": ObjectId("5ef44528af5a1a2a641cd52d"),
"active": true,
"categories": [
"SD-WAN",
"Security and Compliance"
],
"description": "Offering voice, meetings, collaboration and contact center all on one cloud platform.",
"name": "Company Management",
"sub_categories": [
"Solution"
],
"title": "Company Helpline"
}
]
}
]
https://stackoverflow.com/questions/63168397
复制相似问题