本文介绍了在$ project阶段使用$ in运算符过滤数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,无法使用 $ in $ filter 数组聚合运算符中的运算符.

Right now, it's not possible to use the $in operator in the $filter array aggregation operator.

让我们说这是文档架构:

Let's say this is the document schema:

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

我想使用aggregate根据accounts数组的内容获取具有users过滤数组的文档.

I want, using aggregate, to get the documents with filtered array of users based on the contents of the accounts array.

IF $in可以与$filter运算符一起使用,我希望它看起来像这样:

IF the $in would work with the $filter operator, I would expect it to look like this:

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

,并且只返回filtered_users x 在其帐户中的用户以来的第一个用户.

and return in the filtered_users only the first user since x is in his account.

但是,正如我所说,这是行不通的,并且我得到了错误:

But, as I said, this doesn't work and I get the error:

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

现在我知道我可以使用$unwind并使用常规的$match运算符来完成此操作,但是聚合起来将需要更长的时间(并且更丑陋),并且需要使用$group将结果设置为数组-我不想要这个

Now I know I can do it with $unwind and using regular $match operators, but then it will be much longer (and uglier) aggregation with the need of using $group to set the results back as an array - I don't want this

我的问题是,是否还有其他方法可以操纵$filter运算符来获得所需的结果.

My question is, if there is some other way to manipulate the $filter operator to get my desired results.

推荐答案

由于数组的聚合操作不支持$in,因此可以选择使用$setIsSubset.有关此的更多信息,您可以参考链接.汇总查询现在看起来像

Since $in is not supported in aggregate operation for array, the alternative would be for you to use $setIsSubset. For more information on this you can refer this link. The aggregate query would now look like

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

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

This query will return only elements which have [x] as a subset of the array in user.accounts.

这篇关于在$ project阶段使用$ in运算符过滤数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 13:05