我正在尝试为mongoDB
的{{1}}框架创建一个复杂的查询。它需要一个以编程方式添加aggregate
和$and
。
这是我对象的当前结构:
$or
但是,为了使对象有用,我需要重新构造它,以便它同时使用const inputObject = {
"details.blackBottom": { "in": ["A","B","C","D"] },
"details.blackTop": { "in": ["L","M"] },
"details.redBottom": { "in": ["A","B","C","D"] },
"details.redTop": { "in": ["L","M"] },
"details.greenBottom": { "in": ["A","B","C","D"] },
"details.greenTop": { "in": ["L","M"] }
}
和$or
。最终输出应如下所示:
$and
请注意,const outputObject = {
"$and": [
{
"$or" : [
{"details.blackBottom": { "in": ["A","B","C","D"] }},
{"details.redBottom": { "in": ["A","B","C","D"] }},
{"details.greenBottom": { "in": ["A","B","C","D"] }}
]
},
{
"$or" : [
{"details.blackTop": { "in": ["L","M"] } },
{"details.redTop": { "in": ["L","M"] } },
{"details.greenTop": { "in": ["L","M"] } }
]
}
]
}
组件按$or
和Bottom
分组。
如何将Top
转换为所需的inputObject
?
答案 0 :(得分:2)
您可以使用filter
和map
方法的组合来实现这一目标:
const inputObject = {
"details.blackBottom": { "in": ["A","B","C","D"] },
"details.blackTop": { "in": ["L","M"] },
"details.redBottom": { "in": ["A","B","C","D"] },
"details.redTop": { "in": ["L","M"] },
"details.greenBottom": { "in": ["A","B","C","D"] },
"details.greenTop": { "in": ["L","M"] }
}
const outputObject = {
$and: ["Bottom", "Top"].map( side => ({
$or: Object.keys(inputObject)
.filter( key => key.endsWith(side) )
.map( key => ({ [key]: inputObject[key] }) )
}) )
};
console.log(outputObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }