gpt4 book ai didi

node.js - Mongoose :如果对象数组中的数组中存在值,则过滤数据

转载 作者:行者123 更新时间:2023-12-04 17:26:16 25 4
gpt4 key购买 nike

我有一个使用聚合的 Mongoose 查询,我根据对象数组中的值过滤数据,但由于需求变化而遇到麻烦。

这是我的数据在 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”)过滤服务,之前类别是单一的,现在是一系列值,因为一项服务可以属于多个类别

以前的解决方案我用于单一类别值的 Mongoose 查询如下:

db.Collection("suppliers").aggregate([
{
$project: {
services: {
$filter: {
input: "$services",
as: "services",
cond: { $eq: ["$$services.category", "SD-WAN" ] },
},
},
},
},
{ $match: { services: { $exists: true, $not: { $size: 0 } } } },
]);

我在尝试在 $$services.categories 中搜索 SD-WAN 时遇到问题,这是一个值数组。有什么方法可以更新上述查询以使用 $eq 管道运算符或其他一些解决方案在 services.categories 数组中搜索值。

预期结果

"_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"
],
}
]

如果有人能帮我解决这个问题,我将不胜感激。如果需要更多信息,请询问。谢谢。

最佳答案

这里是您要查找的内容。

[
{
$unwind: "$services"
},
{
$match: {
"services.categories": "SD-WAN"
}
},
{
$group: {
_id: "$_id",
active: {
$first: "$active"
},
name: {
$first: "$name"
},
contacts: {
$first: "$contacts"
},
services: {
$addToSet: "$services"
}
}
}
]
  1. 使用$unwind 展开数组
  2. 使用$match进行过滤
  3. 使用 $group 将其分组。

我们仅扁平化服务。这就是为什么我使用 $addToSet

工作 Mongo playground

关于node.js - Mongoose :如果对象数组中的数组中存在值,则过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63168397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com