我已经在使用 Mongo db 聚合查询来获取输出数组。 email 将是查询中输入的电子邮件数组。
**aggregateQuery** = [
{
'$match': {
'email': {
'$in':
['[email protected]', '[email protected]', '[email protected]']
},
'deleted': false
}
},
{< Some more logics here >},
{ '$project': { 'email': 1, 'refId': '$dataArray._id' } }
];
**Output**: [
{
_id: 't1',
email: '[email protected]',
refId: ['ref1', 'ref2', 'ref3','ref4','ref5']
},
{
_id: 't2',
email: '[email protected]',
refId: ['ref1', 'ref2','ref5',ref'82']
},
{
_id: 't3',
email: '[email protected]',
refId: ['ref2', 'ref5','ref77']
}
]
所以现在我想更新我的查询,以便它给出 common(或交集) refids 作为输出,记住输入(或输出)不限于 3。
**Expected Output** : [
Common_RefIds:['ref2', 'ref5']
]
您需要将所有 refId 数组组合成一个数组数组,然后使用 $setIntersection 减少数组以仅保留公共元素。
管道示例:
[
{"$match": {
"email": {"$in": [
"[email protected]",
"[email protected]",
"[email protected]"
]},
"deleted": false
}},
{$group: {
_id: null,
refId_arrays: {$push: "$refId"},
first_array: {$first: "$refId"}
}},
{$project: {
common_refId: {$reduce: {
input: "$refId_arrays",
initialValue: "$first_array",
in: {$setIntersection: ["$$this","$$value"]}
}}
}}
]