【发布时间】:2020-09-24 01:50:18
【问题描述】:
我在 Mongo DB 中有一个看起来像这样的集合 -
const clientsColection = {
"_id" : ObjectId("5ec8492c27ecdc17362b86cb"),
"clientName" : "data" ,
"users" : [
{
"roles" : [],
"operations" : [],
"_id" : ObjectId("5ecac60ab527bd0ba4a615cf"),
"isAdmin" : false,
"username" : "Adduser"
},
{
"roles" : [],
"operations" : [],
"_id" : ObjectId("5ecac60ab527bd0ba4a616cf"),
"isAdmin" : false,
"username" : "new"
}
],
"kpiObj" : [
{
"kpiName" : "epsilon",
"resultObj" : {
"result" : [
{
"mark" : 4,
"plz" : "01069"
},
{
"mark" : 5,
"plz" : "01067"
}
],
}
},
{
"kpiName" : "epsilon2",
"resultObj" : {
"result" : [
{
"mark" : 3,
"plz" : "01069"
},
{
"mark" : 1,
"plz" : "01067"
}
],
}
}
]
}
我正在尝试使用 aggregate、project、filter 运算符对嵌套的对象数组执行过滤器,但我还没有成功获得预期的输出。
我想实现以下目标:-
-
阶段 1:将
users数组对象与users.username匹配并检索匹配的对象数组(始终只有 1 个)。 -
阶段 2:将阶段 1 的输出与
kpiObj中的kpiName匹配,并检索匹配的对象数组(始终只有一个)。 -
第 3 阶段。将第 2 阶段的输出与
resultObj中的mark匹配,并检索匹配的对象数组。
在过去的 3 天里,我观看了几个教程并解决了几个堆栈溢出问题,但未能获得预期的输出。 通过使用以下查询,我已经能够获得 stage1 的预期输出。任何帮助将不胜感激。
db.getCollection("clientsCollection").aggregate([
{ $match: { 'users.username': 'Adduser' } },
{
$project: {
users: {
$filter: {
input: '$users',
as: 'user',
cond: { $eq: ['$$user.username', 'Adduser'] }
}
}, 'kpiObj.kpiName':1, 'kpiObj.resultObj.result.score':1 , 'kpiObj.resultObj.result.plz':1
}
}
])
输出*
为了匹配username 为Adduser,kpiObj.kpiName 为epsilon 和kpiObj.resultObj.result.mark 为4,我期待以下输出:-
const clientsColection = {
"_id" : ObjectId("5ec8492c27ecdc17362b86cb"),
"clientName" : "data" ,
"users" : [
{
"username" : "Adduser"
}
],
"kpiObj" : [
{
"kpiName" : "epsilon",
"resultObj" : {
"result" : [
{
"mark" : 4,
"plz" : "01069"
}
],
}
}
]
}
【问题讨论】:
-
在该示例中,应针对
kpiName测试哪些标准?您想在输出文档方面得到什么? -
@Joe :- 我已经更新了预期的输出。
标签: mongodb mongoose mongodb-query aggregation-framework