Mongodb $or操作,用于在两个不同数组中匹配同一元素
假设我在两个不同的文档中有两个不同的数组,即Mongodb $or操作,用于在两个不同数组中匹配同一元素,mongodb,express,aggregation-framework,Mongodb,Express,Aggregation Framework,假设我在两个不同的文档中有两个不同的数组,即carPolicies[]和paPolicies[]。显然,有policy对象包含agent的键 [ { "_id": "_id", "name": "qwe", "password": "pw", "carPolicies": [ { "p
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[]
whereagent
: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[]
whereagent
:47。如何添加$或
,以便能够在代理
为47的查询中检查两个数组?或者还有其他更适合我的用例的操作符吗
我的预期结果应该是:
[
{
"policy": [
{
"agent": "47"
}
]
},
{
"policy": [
{
"agent": "47"
}
]
},
{
"policy": [
{
"agent": "47"
}
]
},
{
"policy": [
{
"agent": "47"
}
]
}
]
输出中应该有4个策略,因为在我的示例中,只有4个策略具有代理
=47,其中一个策略具有不应检索的代理
=99。您可以尝试
- 使用
$或
- 使用和
$concatarray将
添加到筛选器中作为输入paPolicies.policy
解构$unwind
数组策略
将$project
转换为数组策略
您想在$match或$filter中添加
或条件的位置?@turivishal您的意思是什么?我的意思是您想在哪里检查政策的条件?在$match pipeline或$project pipeline filter中?@turivishal最好在$match pipeline中。我检查了您的mongo游乐场链接,它没有从paPolicies[]
检索策略,其中agent
是47,您可以从我的代码中看到,我有一个$filter
,其中input
是$carPolicies.policy
。如果改为在$filter
中执行该操作会怎么样?是的,这就是我问你的原因,你能从你的数据集中添加预期结果吗?我将在我的问题中添加它以进行澄清。谢谢。您需要验证_id是否与集合中的id相同,并在集合中检查其对象id或字符串对象id。是的,我有。我已经解决了这个问题。我需要在我的查询中明确添加_id是objectId。
db.collection.aggregate([
{
$match: {
$or: [
{ "carPolicies.policy.agent": req.params.name },
{ "paPolicies.policy.agent": req.params.name }
]
}
},
{
$project: {
policy: {
$filter: {
input: {
$concatArrays: ["$carPolicies.policy", "$paPolicies.policy"]
},
as: "police",
cond: { $eq: ["$$police.agent", req.params.name] }
}
}
}
},
{ $unwind: "$policy" },
{
$project: {
_id: 0,
policy: ["$policy"]
}
}
])