翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$setDifference
バージョン 4.0 の新機能。
Amazon DocumentDB の $setDifference演算子は、2 つのセットを比較し、最初のセットにはあるが、2 番目のセットにはない要素を返すために使用されます。この演算子は、2 つのセット間で一意の要素を見つけるのに役立ちます。
パラメータ
例 (MongoDB シェル)
次の例は、 $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配列を配列と比較["banana", "cherry", "date"]し、fruits配列内の一意の要素を返します。
コードの例
$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()