$in - Amazon DocumentDB

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

$in

L'operatore $in di aggregazione verifica se un valore specificato esiste all'interno di un array. Restituisce true se il valore viene trovato nell'array e in false altro modo.

Parametri

  • value: Il valore da cercare.

  • array: L'array in cui cercare.

Esempio (MongoDB Shell)

L'esempio seguente dimostra l'utilizzo dell'$inoperatore per verificare se esiste una competenza specifica nel set di competenze di ciascun dipendente.

Crea documenti di esempio

db.employees.insertMany([ { _id: 1, name: "Sarah", skills: ["Python", "JavaScript", "SQL"] }, { _id: 2, name: "Mike", skills: ["Java", "C++", "Go"] }, { _id: 3, name: "Emma", skills: ["Python", "Ruby", "Rust"] } ]);

Esempio di query

db.employees.aggregate([ { $project: { name: 1, hasPython: { $in: ["Python", "$skills"] } } } ]);

Output

[ { _id: 1, name: 'Sarah', hasPython: true }, { _id: 2, name: 'Mike', hasPython: false }, { _id: 3, name: 'Emma', hasPython: true } ]

Esempi di codice

Per visualizzare un esempio di codice per l'utilizzo dell'operatore di $in aggregazione, scegli la scheda relativa alla lingua che desideri utilizzare:

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('employees'); const result = await collection.aggregate([ { $project: { name: 1, hasPython: { $in: ["Python", "$skills"] } } } ]).toArray(); console.log(result); await 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['employees'] result = list(collection.aggregate([ { '$project': { 'name': 1, 'hasPython': { '$in': ['Python', '$skills'] } } } ])) print(result) client.close() example()