Docs HomeMongoDB Manual

$setEquals (aggregation)

On this page本页内容

Definition定义

$setEquals

Compares two or more arrays and returns true if they have the same distinct elements and false otherwise.比较两个或多个数组,如果它们具有相同的不同元素,则返回true,否则返回false

$setEquals has the following syntax:具有以下语法:

{ $setEquals: [ <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行为

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

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

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

Example实例

Consider a bakeryOrders collection with the following documents:考虑一个包含以下文档的bakeryOrders集合:

db.bakeryOrders.insertMany( [
{ _id: 0, cakes: ["chocolate", "vanilla"], cupcakes: ["chocolate", "vanilla"] },
{ _id: 1, cakes: ["chocolate", "vanilla"], cupcakes: ["vanilla", "chocolate"] },
{ _id: 2, cakes: ["chocolate", "chocolate"], cupcakes: ["chocolate"] },
{ _id: 3, cakes: ["vanilla"], cupcakes: ["chocolate"] },
{ _id: 4, cakes: ["vanilla"], cupcakes: [] }
] )

The following operation uses the $setEquals operator to determine if the cakes array and the cupcakes array in each order contain the same flavors:以下操作使用$setEquals运算符来确定每个顺序中的cakes数组和cupcakes数组是否包含相同的口味:

db.bakeryOrders.aggregate(
[
{
$project: {
_id: 0,
cakes: 1,
cupcakes: 1,
sameFlavors: { $setEquals: [ "$cakes", "$cupcakes" ] }
}
}
] )
Note

$project

The $project stage specifies which fields are included in the output documents. $project阶段指定输出文档中包含哪些字段。In this example, the $project stage:在本例中,$project阶段:

  • Excludes the _id field from the output.从输出中排除_id字段。
  • Includes the cakes and cupcakes fields in the output.在输出中包括cakescupcakes字段。
  • Outputs the result of the $setEquals operator in a new field called sameFlavors.在名为sameFlavors的新字段中输出$setEquals运算符的结果。

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

{
cakes: [ "chocolate", "vanilla" ],
cupcakes: [ "chocolate", "vanilla" ],
sameFlavors: true
},
{
cakes: [ "chocolate", "vanilla" ],
cupcakes: [ "vanilla", "chocolate" ],
sameFlavors: true
},
{
cakes: [ "chocolate", "chocolate" ],
cupcakes: [ "chocolate" ],
sameFlavors: true
},
{
cakes: [ "vanilla" ],
cupcakes: [ "chocolate" ],
sameFlavors: false
},
{
cakes: [ "vanilla" ],
cupcakes: [],
sameFlavors: false
}