mongodb - 使用 $match 从具有相同键值的不同数组中查询
问题描述
假设我有两个文档的这个简单 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
}
}
])
我知道上面的代码是错误的,但我觉得这是我目前能找到的最接近解决方案的方法,希望能对我想要实现的目标有所了解。
解决方案
推荐阅读
- odoo - 如何更改 /odoo/src 中的文件并提交并与生产分支合并?
- javascript - 类型错误:func.apply 不是函数
- go - 如何在 go 中调用 user32.dll 的 EnumDisplaySettingsA
- javascript - 更改元素/节点 style.display 时,dom 缺少一些元素
- docusignapi - 如何将 Docusign 集成到 Bonita webapp
- r - svd(X) 中的错误:“x”中的值无限或缺失
- indy - Lazarus RingCentral API RingOut TIdHTTP 中的 Indy 10
- node.js - 在 react-native 中上传 blob/文件,内容为空
- arrays - 在 xslt 1.0 中格式化值数组
- javascript - 如何从 javascript 代码向使用 socket.io 连接的所有用户发出结果