ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

$setEquals (aggregation)

項目一覧

$setEquals

Compares two or more arrays and returns true if they have the same distinct elements and false otherwise.

$setEqualsの構文は次のとおりです。

{ $setEquals: [ <expression1>, <expression2>, ... ] }

The arguments can be any valid as long as they each resolve to an array. For more information on expressions, see 式演算子.

$setEquals performs set operation on arrays, treating arrays as sets. If an array contains duplicate entries, $setEquals ignores the duplicate entries. $setEquals ignores the order of the elements.

セットにネストされた配列要素が含まれている場合、 $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: [] }
] )

The following operation uses the $setEquals operator to determine if the cakes array and the cupcakes array in each order contain the same flavors:

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. In this example, the $project stage:

  • Excludes the _id field from the output.

  • Includes the cakes and cupcakes fields in the output.

  • Outputs the result of the $setEquals operator in a new field called sameFlavors.

この操作は次の結果を返します。

{
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
}

項目一覧