使用 mongoDB $lookup 查找数组中不存在的另一个集合中的文档
Use mongoDB $lookup to find documents in another collection not present inside an array
我正在使用聚合框架来查询一个集合并创建一个活跃玩家数组(直到最后一个 $lookup
),之后我尝试使用 $lookup
和 $pipeline
到 select 来自另一个集合 (users
) 的所有 不 存在于 activeUsers
数组。
我当前的设置有什么方法可以做到这一点吗?
Game.aggregate[{
$match: {
date: {
$gte: ISODate('2021-04-10T00:00:00.355Z')
},
gameStatus: 'played'
}
}, {
$unwind: {
path: '$players',
preserveNullAndEmptyArrays: false
}
}, {
$group: {
_id: '$players'
}
}, {
$group: {
_id: null,
activeUsers: {
$push: '$_id'
}
}
}, {
$project: {
activeUsers: true,
_id: false
}
}, {
$lookup: {
from: 'users',
'let': {
active: '$activeUsers'
},
pipeline: [{
$match: {
deactivated: false,
// The rest of the query works fine but here I would like to
// select only the elements that *aren't* inside
// the array (instead of the ones that *are* inside)
// but if I use '$nin' here mongoDB throws
// an 'unrecognized' error
$expr: {
$in: [
'$_id',
'$$active'
]
}
}
},
{
$project: {
_id: 1
}
}
],
as: 'users'
}
}]
谢谢
对于否定条件,在 $in
运算符之前使用 $not
,
{ $expr: { $not: { $in: ['$_id', '$$active'] } } }
我正在使用聚合框架来查询一个集合并创建一个活跃玩家数组(直到最后一个 $lookup
),之后我尝试使用 $lookup
和 $pipeline
到 select 来自另一个集合 (users
) 的所有 不 存在于 activeUsers
数组。
我当前的设置有什么方法可以做到这一点吗?
Game.aggregate[{
$match: {
date: {
$gte: ISODate('2021-04-10T00:00:00.355Z')
},
gameStatus: 'played'
}
}, {
$unwind: {
path: '$players',
preserveNullAndEmptyArrays: false
}
}, {
$group: {
_id: '$players'
}
}, {
$group: {
_id: null,
activeUsers: {
$push: '$_id'
}
}
}, {
$project: {
activeUsers: true,
_id: false
}
}, {
$lookup: {
from: 'users',
'let': {
active: '$activeUsers'
},
pipeline: [{
$match: {
deactivated: false,
// The rest of the query works fine but here I would like to
// select only the elements that *aren't* inside
// the array (instead of the ones that *are* inside)
// but if I use '$nin' here mongoDB throws
// an 'unrecognized' error
$expr: {
$in: [
'$_id',
'$$active'
]
}
}
},
{
$project: {
_id: 1
}
}
],
as: 'users'
}
}]
谢谢
对于否定条件,在 $in
运算符之前使用 $not
,
{ $expr: { $not: { $in: ['$_id', '$$active'] } } }