gpt4 book ai didi

mongodb - 在 $project 阶段使用 $in 运算符过滤数组

转载 作者:IT老高 更新时间:2023-10-28 13:14:41 26 4
gpt4 key购买 nike

目前,无法使用 $in $filter 中的运算符数组聚合运算符。

假设这是文档架构:

{
_id: 1,
users: [
{
_id: 'a',
accounts: ['x', 'y', 'z']
},
{
_id: 'b',
accounts: ['j','k','l']
}
]
}

我想要,使用 aggregate , 得到过滤数组 users 的文档基于accounts的内容数组。

如果 $in将与 $filter 一起使用运算符,我希望它看起来像这样:

db.test.aggregate([
{
$project: {
'filtered_users': {
$filter: {
input: '$users',
as: 'user',
cond: {
$in: ['$$user.accounts', ['x']]
}
}
}
}
}
])

并返回 filtered_users只有自 x 之后的第一个用户他的帐户中。

但是,正如我所说,这不起作用,我得到了错误:

"invalid operator '$in'"

因为 $filter 不支持它运算符。

现在我知道我可以使用 $unwind并使用常规 $match运算符,但随后需要使用 $group 的聚合时间会更长(也更丑陋)将结果设置为数组 - 我不想要这个

我的问题是,是否有其他方法可以操纵 $filter运算符来获得我想要的结果。

最佳答案

由于数组的聚合操作不支持 $in,因此您可以使用 $setIsSubset。有关这方面的更多信息,您可以引用 this关联。聚合查询现在看起来像

db.test.aggregate([
{
$project: {
'filtered_users': {
$filter: {
input: '$users',
as: 'user',
cond: {
$setIsSubset: [['x'], '$$user.accounts']
}
}
}
}
}])

此查询将仅返回 [x] 作为 user.accounts 中数组子集的元素。

关于mongodb - 在 $project 阶段使用 $in 运算符过滤数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39444888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com