MongoDB聚合运算符:$setIntersection
文章目录
$setIntersection聚合运算符返回两个或多个数组的交集。
语法
{
$setIntersection: [ <array1>, <array2>, ... ] }
字段说明:
参数可以是任何有效的数组表达式。
使用
$setIntersection对数组执行集合操作,将数组视为集合,如果数组包含重复元素,$setIntersection会忽略重复元素,$setIntersection忽略元素的顺序。$setIntersection过滤掉结果中的重复项,输出仅包含唯一元素的数组,输出数组中元素的顺序未指定。- 如果未找到交集(即输入数组不包含公共元素),则
$setIntersection返回一个空数组。 - 如果集合包含嵌套数组元素,则
$setIntersection不会下降到嵌套数组,而处理顶层数组。
| 例如 | 结果 |
|---|---|
{ $setIntersection: [ [ "a", "b", "a" ], [ "b", "a" ] ] } |
[ "b", "a" ] |
{ $setIntersection: [ [ "a", "b" ], [ [ "a", "b" ] ] ] } |
[] |
举例
元素数组举例
使用下面的脚本创建flowers集合:
db.flowers.insertMany( [
{
"_id" : 1, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid" ] },
{
"_id" : 2, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "orchid", "rose", "orchid" ] },
{
"_id" : 3, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid", "jasmine" ] },
{
"_id" : 4, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "jasmine", "rose" ] },
{
"_id" : 5, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ ] },
{
"_id" : 6, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose" ], [ "orchid" ] ] },
{
"_id" : 7, "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose", "orchid" ] ] },
{
"_id" : 8,
MongoDB$setIntersection聚合运算符:查找数组交集与用户角色权限应用实例

最低0.47元/天 解锁文章
528

被折叠的 条评论
为什么被折叠?



