$setIsSubset (aggregation)

On this page本页内容

Definition定义

$setIsSubset

Takes two arrays and returns true when the first array is a subset of the second, including when the first array equals the second array, and false otherwise.获取两个数组,当第一个数组是第二个数组的子集时返回true,包括当第一个数组等于第二个数组时,否则返回false

$setIsSubset has the following syntax:语法如下所示:

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

The arguments can be any valid expression as long as they each resolve to an array. 参数可以是任何有效的表达式,只要它们各自解析为一个数组。For more information on expressions, see Expressions.有关表达式的详细信息,请参阅表达式

Behavior行为

$setIsSubset performs set operation on arrays, treating arrays as sets. 对数组执行集合操作,将数组视为集合。If an array contains duplicate entries, $setIsSubset ignores the duplicate entries. 如果数组包含重复的条目,$setIsSubset将忽略重复的条目。$setIsSubset ignores the order of the elements.忽略元素的顺序。

If a set contains a nested array element, $setIsSubset does not descend into the nested array but evaluates the array at top-level.如果集合包含嵌套数组元素,$setIsSubset不会下降到嵌套数组中,而是在顶级对数组求值。

Example示例Result
{ $setIsSubset: [ [ "a", "b", "a" ], [ "b", "a" ] ] }
true
{ $setIsSubset: [ [ "a", "b" ], [ [ "a", "b" ] ] ] }
false

Example示例

Consider an experiments collection with the following documents:考虑一个experiments集合,带有下列文档:

{ "_id" : 1, "A" : [ "red", "blue" ], "B" : [ "red", "blue" ] }
{ "_id" : 2, "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ] }
{ "_id" : 3, "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ] }
{ "_id" : 4, "A" : [ "red", "blue" ], "B" : [ "green", "red" ] }
{ "_id" : 5, "A" : [ "red", "blue" ], "B" : [ ] }
{ "_id" : 6, "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ] }
{ "_id" : 7, "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ] }
{ "_id" : 8, "A" : [ ], "B" : [ ] }
{ "_id" : 9, "A" : [ ], "B" : [ "red" ] }

The following operation uses the $setIsSubset operator to determine if the A array is a subset of the B array:以下操作使用$setIsSubset运算符确定A数组是否为B数组的子集:

db.experiments.aggregate(
   [
     { $project: { A:1, B: 1, AisSubset: { $setIsSubset: [ "$A", "$B" ] }, _id:0 } }
   ]
)

The operation returns the following results:操作返回以下结果:

{ "A" : [ "red", "blue" ], "B" : [ "red", "blue" ], "AisSubset" : true }
{ "A" : [ "red", "blue" ], "B" : [ "blue", "red", "blue" ], "AisSubset" : true }
{ "A" : [ "red", "blue" ], "B" : [ "red", "blue", "green" ], "AisSubset" : true }
{ "A" : [ "red", "blue" ], "B" : [ "green", "red" ], "AisSubset" : false }
{ "A" : [ "red", "blue" ], "B" : [ ], "AisSubset" : false }
{ "A" : [ "red", "blue" ], "B" : [ [ "red" ], [ "blue" ] ], "AisSubset" : false }
{ "A" : [ "red", "blue" ], "B" : [ [ "red", "blue" ] ], "AisSubset" : false }
{ "A" : [ ], "B" : [ ], "AisSubset" : true }
{ "A" : [ ], "B" : [ "red" ], "AisSubset" : true }