$setIsSubset(聚合)
MongoDB5.0 已于 10 月2024 结束生命周期。不再支持此版本的文档。要升级5.0 部署,请参阅 MongoDB6 。0 升级程序。
定义
$setIsSubset
接受两个数组,当第一个数组是第二个数组的子集时(包括第一个数组等于第二个数组时)返回
true
,否则返回false
。$setIsSubset
通过以下语法实现:{ $setIsSubset: [ <expression1>, <expression2> ] }
行为
$setIsSubset
对数组执行集合操作,将数组视为集合。如果数组包含重复条目,$setIsSubset
会忽略重复条目。$setIsSubset
会忽略元素的顺序。
如果集合包含嵌套数组元素,$setIsSubset
不会下降进入嵌套数组,而是在顶层计算数组。
例子 | 结果 | |
---|---|---|
|
| |
|
|
例子
考虑包含以下文档的 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, "flowerFieldA" : [ ], "flowerFieldB" : [ ] }, { "_id" : 9, "flowerFieldA" : [ ], "flowerFieldB" : [ "rose" ] } ] )
以下操作使用$setIsSubset
操作符来确定flowerFieldA
大量是否为flowerFieldB
大量的子集:
db.flowers.aggregate( [ { $project: { flowerFieldA:1, flowerFieldB: 1, AisSubset: { $setIsSubset: [ "$flowerFieldA", "$flowerFieldB" ] }, _id:0 } } ] )
操作返回以下结果:
{ "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid" ], "AisSubset" : true } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "orchid", "rose", "orchid" ], "AisSubset" : true } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "rose", "orchid", "jasmine" ], "AisSubset" : true } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ "jasmine", "rose" ], "AisSubset" : false } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ ], "AisSubset" : false } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose" ], [ "orchid" ] ], "AisSubset" : false } { "flowerFieldA" : [ "rose", "orchid" ], "flowerFieldB" : [ [ "rose", "orchid" ] ], "AisSubset" : false } { "flowerFieldA" : [ ], "flowerFieldB" : [ ], "AisSubset" : true } { "flowerFieldA" : [ ], "flowerFieldB" : [ "rose" ], "AisSubset" : true }