

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# \$1setDifference
<a name="setDifference"></a>

バージョン 4.0 の新機能。

Amazon DocumentDB の `$setDifference`演算子は、2 つのセットを比較し、最初のセットにはあるが、2 番目のセットにはない要素を返すために使用されます。この演算子は、2 つのセット間で一意の要素を見つけるのに役立ちます。

**パラメータ**
+ `firstSet` : 比較する最初のセット。
+ `secondSet` : 比較する 2 番目のセット。

## 例 (MongoDB シェル)
<a name="setDifference-examples"></a>

次の例は、 `$setDifference`演算子を使用して 2 つのセット間の一意の要素を検索する方法を示しています。

**サンプルドキュメントを作成する**

```
db.collection.insertMany([
  { _id: 1, fruits: ["apple", "banana", "cherry", "date"] },
  { _id: 2, fruits: ["banana", "cherry", "date", "elderberry"] }
]);
```

**クエリの例**

```
db.collection.aggregate([
  {
    $project: {
      uniqueFruits: { $setDifference: ["$fruits", ["banana", "cherry", "date"]] }
    }
  }
]);
```

**出力**

```
[
  { "_id": 1, "uniqueFruits": ["apple"] },
  { "_id": 2, "uniqueFruits": ["elderberry"] }
]
```

クエリは次のステップを実行します。

1. `$project` ステージを使用して、ドキュメント`uniqueFruits`ごとに新しいフィールドを作成します。

2. `$setDifference` 演算子は`fruits`配列を配列と比較`[&quot;banana&quot;, &quot;cherry&quot;, &quot;date&quot;]`し、`fruits`配列内の一意の要素を返します。

## コードの例
<a name="setDifference-code"></a>

`$setDifference` コマンドを使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ Node.js ]

Node.js アプリケーションで `$setDifference`演算子を使用する方法の例を次に示します。

```
const { MongoClient } = require('mongodb');

async function main() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('mycollection');

  // Insert sample documents
  await collection.insertMany([
    { _id: 1, fruits: ["apple", "banana", "cherry", "date"] },
    { _id: 2, fruits: ["banana", "cherry", "date", "elderberry"] }
  ]);

 // Query using $setDifference
  const result = await collection.aggregate([
    {
      $project: {
        uniqueFruits: { $setDifference: ["$fruits", ["banana", "cherry", "date"]] }
      }
    }
  ]).toArray();

  console.log(result);
  await client.close();
}

main();
```

------
#### [ Python ]

Python アプリケーションで `$setDifference`演算子を使用する方法の例を次に示します。

```
from pymongo import MongoClient

def main():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client['test']
    collection = db['mycollection']

    # Insert sample documents
    collection.insert_many([
        {'_id': 1, 'fruits': ["apple", "banana", "cherry", "date"]},
        {'_id': 2, 'fruits': ["banana", "cherry", "date", "elderberry"]}
    ])

    # Query using $setDifference
    result = list(collection.aggregate([
        {
            '$project': {
                'uniqueFruits': {'$setDifference': ['$fruits', ["banana", "cherry", "date"]]}
            }
        }
    ]))

    print(result)
    client.close()

if __name__ == '__main__':
    main()
```

------