【发布时间】:2020-08-19 08:48:14
【问题描述】:
假设我在两个不同的文档中有两个不同的数组,即carPolicies[] 和paPolicies[]。显然,有policy 对象包含agent 的键。
[
{
"_id": "_id",
"name": "qwe",
"password": "pw",
"carPolicies": [
{
"policy": {
"agent": "47"
}
},
],
"paPolicies": [
{
"policy": {
"agent": "47"
}
},
]
},
{
"_id": "_id",
"name": "rty",
"password": "wp",
"carPolicies": [
{
"policy": {
"agent": "47"
}
},
],
"paPolicies": [
{
"policy": {
"agent": "47"
}
},
{
"policy": {
"agent": "99"
}
}
]
}
]
如果我进行如下查询,它将仅从carPolicies[] 向我返回政策,其中agent: 47。
db.collection('users').aggregate([
// get just the documents that contain an agent key where agent is === 47
{ $match: { 'carPolicies.policy.agent': req.params.name } },
{
$project: {
policy: {
$filter: {
input: '$carPolicies.policy',
as: 'police',
cond: { $eq: ['$$police.agent', req.params.name ]}
}
}
}
}
])
但是,我想修改相同的查询以检查 paPolicies[] where agent: 47 也。如何添加$or 以便能够在agent 为47 的一个查询中检查两个数组?还是有其他更适合我用例的运算符?
我的预期结果应该输出:
[
{
"policy": [
{
"agent": "47"
}
]
},
{
"policy": [
{
"agent": "47"
}
]
},
{
"policy": [
{
"agent": "47"
}
]
},
{
"policy": [
{
"agent": "47"
}
]
}
]
输出中应该有 4 个策略,因为在我的示例中,只有 4 个策略具有 agent = 47,其中一个策略具有不应检索的 agent = 99。
【问题讨论】:
-
您想在 $match 或 $filter 中添加
or条件的位置? -
@turivishal 你是什么意思?
-
我的意思是你想在哪里检查
paPolicies的条件?在 $match 管道还是在 $project 管道过滤器中? -
@turivishal 最好在 $match 管道中。
标签: mongodb express aggregation-framework