$setEquals(聚合)
定义
$setEquals
比较两个或多个数组,如果它们具有相同的不同元素,则返回
true
,否则返回false
。$setEquals
通过以下语法实现:{ $setEquals: [ <expression1>, <expression2>, ... ] }
行为
$setEquals
对数组执行集合操作,将数组视为集合。如果数组包含重复条目,$setEquals
会忽略重复条目。$setEquals
会忽略元素的顺序。
如果集合包含嵌套数组元素,$setEquals
不会下降进入嵌套数组,而是在顶层计算数组。
例子 | 结果 |
---|---|
{ $setEquals: [ [ "a", "b", "a" ], [ "b", "a" ] ] } | true |
{ $setEquals: [ [ "a", "b" ], [ [ "a", "b" ] ] ] } | false |
例子
请考虑包含以下文档的 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: [] } ] )
以下操作使用$setEquals
操作符来确定每个订单中的cakes
大量和cupcakes
大量是否包含相同的口味:
db.bakeryOrders.aggregate( [ { $project: { _id: 0, cakes: 1, cupcakes: 1, sameFlavors: { $setEquals: [ "$cakes", "$cupcakes" ] } } } ] )
注意
$project
操作返回以下结果:
{ 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 }