Docs 菜单
Docs 主页
/
MongoDB Manual
/ / /

$setIsSubset(聚合)

在此页面上

  • 定义
  • 行为
  • 例子
$setIsSubset

接受两个数组,当第一个数组是第二个数组的子集时(包括第一个数组等于第二个数组时)返回true ,否则返回false

$setIsSubset 通过以下语法实现:

{ $setIsSubset: [ <expression1>, <expression2> ] }

参数可以是任何有效的表达式,只要它们都能解析为大量即可。 有关表达式的更多信息,请参阅表达式。

$setIsSubset对数组执行集合操作,将数组视为集合。如果数组包含重复条目,$setIsSubset 会忽略重复条目。$setIsSubset 会忽略元素的顺序。

如果集合包含嵌套数组元素,$setIsSubset不会下降进入嵌套数组,而是在顶层计算数组。

例子
结果
{ $setIsSubset: [ [ "a", "b", "a" ], [ "b", "a" ] ] }
true
{ $setIsSubset: [ [ "a", "b" ], [ [ "a", "b" ] ] ] }
false

考虑包含以下文档的 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 }

后退

$setIntersection

在此页面上