Mongodb聚合。我需要过滤在多个数组中匹配的结果
Mongodb aggregation. I need to filter results that matches within multiple arrays
我有一个查询需要 $in 参数不同的数组。第一个是 openBehaviourIds,第二个是 closeBehaviours。
我想避免重复的代码并使用聚合进行一次查询以获得结果
{openBehaviours:[{},{}...],closeBehaviours:[{},{},{}...]} 代替使用:
- const openBehaviours = await behavioursCollection.aggregate([...])
- const closeBehaviours = await behavioursCollection.aggregate([...])
打开和关闭 behaviorId 是字符串数组
获取以下两种行为的完整查询(几乎相同):
const openBehaviours = await behavioursCollection.aggregate([
{ $match: { 'behaviourId': { $in: openBehaviourIds } } }, {
$lookup: {
from: 'colors',
localField: 'domainId',
foreignField: 'domainId',
as: 'color'
}
}, { $unwind: '$color' }
], { session }).toArray()
const closeBehaviours = await behavioursCollection.aggregate([
{ $match: { 'behaviourId': { $in: closeBehaviours } } }, {
$lookup: {
from: 'colors',
localField: 'domainId',
foreignField: 'domainId',
as: 'color'
}
}, { $unwind: '$color' }
], { session }).toArray()
如何将其合并到一个查询中以使其 crystal 清晰?
感谢帮助
您可以使用 $facet 运算符来实现。
behavioursCollection.aggregate([
{$facet:{
"openBehaviours":[
{ $match: { 'behaviourId': { $in: openBehaviourIds } } },
{
$lookup: {
from: 'colors',
localField: 'domainId',
foreignField: 'domainId',
as: 'color'
}
},
{ $unwind: '$color' }
],
"closeBehaviours":[
{ $match: { 'behaviourId': { $in: closeBehaviours } } },
{
$lookup: {
from: 'colors',
localField: 'domainId',
foreignField: 'domainId',
as: 'color'
}
},
{ $unwind: '$color' }
]
}}]);
我有一个查询需要 $in 参数不同的数组。第一个是 openBehaviourIds,第二个是 closeBehaviours。 我想避免重复的代码并使用聚合进行一次查询以获得结果 {openBehaviours:[{},{}...],closeBehaviours:[{},{},{}...]} 代替使用:
- const openBehaviours = await behavioursCollection.aggregate([...])
- const closeBehaviours = await behavioursCollection.aggregate([...])
打开和关闭 behaviorId 是字符串数组
获取以下两种行为的完整查询(几乎相同):
const openBehaviours = await behavioursCollection.aggregate([
{ $match: { 'behaviourId': { $in: openBehaviourIds } } }, {
$lookup: {
from: 'colors',
localField: 'domainId',
foreignField: 'domainId',
as: 'color'
}
}, { $unwind: '$color' }
], { session }).toArray()
const closeBehaviours = await behavioursCollection.aggregate([
{ $match: { 'behaviourId': { $in: closeBehaviours } } }, {
$lookup: {
from: 'colors',
localField: 'domainId',
foreignField: 'domainId',
as: 'color'
}
}, { $unwind: '$color' }
], { session }).toArray()
如何将其合并到一个查询中以使其 crystal 清晰? 感谢帮助
您可以使用 $facet 运算符来实现。
behavioursCollection.aggregate([
{$facet:{
"openBehaviours":[
{ $match: { 'behaviourId': { $in: openBehaviourIds } } },
{
$lookup: {
from: 'colors',
localField: 'domainId',
foreignField: 'domainId',
as: 'color'
}
},
{ $unwind: '$color' }
],
"closeBehaviours":[
{ $match: { 'behaviourId': { $in: closeBehaviours } } },
{
$lookup: {
from: 'colors',
localField: 'domainId',
foreignField: 'domainId',
as: 'color'
}
},
{ $unwind: '$color' }
]
}}]);