$setIntersection - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$setIntersection

Amazon DocumentDB 中的$setIntersection运算符用于返回两个或多个数组之间的公共元素。此运算符在处理数据集时特别有用,它允许您找到多个数据集的交集。

参数

  • array1: 第一个相交的数组。

  • array2: 第二个要相交的数组。

  • arrayN:(可选)要相交的其他数组。

示例(MongoDB 外壳)

以下示例演示如何使用$setIntersection运算符来查找两个数组之间的公共元素。

创建示例文档

db.collection.insertMany([ { _id: 1, colors: ["red", "blue", "green"] }, { _id: 2, colors: ["blue", "yellow", "orange"] }, { _id: 3, colors: ["red", "green", "purple"] } ])

查询示例

db.collection.aggregate([ { $project: { _id: 1, commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] } } } ])

输出

[ { "_id": 1, "commonColors": ["red", "blue", "green"] }, { "_id": 2, "commonColors": ["blue"] }, { "_id": 3, "commonColors": ["red", "green"] } ]

代码示例

要查看使用该$setIntersection命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function example() { 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'); const result = await collection.aggregate([ { $project: { _id: 1, commonColors: { $setIntersection: ["$colors", ["red", "blue", "green"]] } } } ]).toArray(); console.log(result); client.close(); } example();
Python
from pymongo import MongoClient def example(): 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'] result = list(collection.aggregate([ { '$project': { '_id': 1, 'commonColors': { '$setIntersection': ["$colors", ["red", "blue", "green"]] } } } ])) print(result) client.close() example()