【发布时间】:2020-08-14 18:05:39
【问题描述】:
假设我有两个文档的这个简单 JSON 数据,两个文档都有两个不同的数组,即 carPolicies 和 paPolicies。在这些数组中是名为policy 的对象,其中包含一个键“代理”,其值为“47”。
{
"_id": {
"$oid": "some_id"
},
"name": "qwe",
"password": "pw",
"carPolicies": [
{
"policy": {
"agent": "47"
}
},
{
"policy": {
"agent": "47"
}
}
],
"paPolicies": [
{
"policy": {
"agent": "47"
}
},
{
"policy": {
"agent": "47"
}
}
]
}
{
"_id": {
"$oid": "some_id"
},
"name": "rty",
"password": "wp",
"carPolicies": [
{
"policy": {
"agent": "47"
}
},
{
"policy": {
"agent": "47"
}
}
],
"paPolicies": [
{
"policy": {
"agent": "47"
}
},
{
"policy": {
"agent": "47"
}
}
]
}
使用 mongoDB 的 $match 运算符,我如何提出一个查询,如果代理值在任一数组中为 47,它会返回文档的名称?
这是我目前拥有的:
db.collection('users').aggregate([
// Get just the docs that contain an agent element where agent is === req.params.name
{$match: {$or: [{'paPolicies.policy.agent': req.params.name}, {'carPolicies.policy.agent': req.params.name}]} },
{
$project: {
policy: {
$filter: {
// how to do an 'or' operator at 'input' so it can be input: '$paPolicies.policy || $carPolicies.policy'
input: '$paPolicies.policy',
as: 'police',
cond: { $eq: ['$$police.agent', req.params.name]}
}
},
_id: 1, name: 1
}
}
])
我知道上面的代码是错误的,但我觉得这是我目前能找到的最接近解决方案的方法,希望能说明我想要实现的目标。
【问题讨论】:
标签: mongodb express aggregation-framework