Mongodb 使用$match从具有相同键值的不同数组中查询
假设我有两个文档的简单JSON数据,它们都有两个不同的数组,即Mongodb 使用$match从具有相同键值的不同数组中查询,mongodb,express,aggregation-framework,Mongodb,Express,Aggregation Framework,假设我有两个文档的简单JSON数据,它们都有两个不同的数组,即carPolicies和paPolicies。这些数组中有名为policy的对象,其中包含一个键“agent”,其值为“47” { "_id": { "$oid": "some_id" }, "name": "qwe", "password": "pw&quo
carPolicies
和paPolicies
。这些数组中有名为policy
的对象,其中包含一个键“agent”,其值为“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
}
}
])
我知道上面的代码是错误的,但我觉得这是我目前能找到的最接近解决方案,希望能让我了解我想要实现的目标。如果我得到了正确的需求。在
.find()查询中使用作为第二个参数怎么样
db.collection.find({
$or: [
{
"carPolicies.policy.agent": "47"
},
{
"paPolicies.policy.agent": "47"
}
]
},
{
"_id": 1,
"name": 1
})
让我试试这个,我会给你回复的@如果这就是你想要的,我已经接受了你的答案。简单明了。在看了你的解决方案之后,我可能已经过度思考了我的问题。哈哈,谢谢你帮助我发现了mongo游乐场!