$setEquals (aggregation)
On this page本页内容
Definition定义
$setEquals-
Compares two or more arrays and returns比较两个或多个数组,如果它们具有相同的不同元素,则返回trueif they have the same distinct elements andfalseotherwise.true,否则返回false。$setEqualshas 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不会下降到嵌套数组中,而是在顶级计算数组。
{ $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" ] }
}
}
] )
$project
The $project stage specifies which fields are included in the output documents. $project阶段指定输出文档中包含哪些字段。In this example, the 在本例中,$project stage:$project阶段:
Excludes the从输出中排除_idfield from the output._id字段。Includes the在输出中包括cakesandcupcakesfields in the output.cakes和cupcakes字段。Outputs the result of the在名为$setEqualsoperator in a new field calledsameFlavors.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
}