$and - Amazon DocumentDB

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

$and

Operator $and agregasi mengevaluasi beberapa ekspresi dan mengembalikan true hanya jika semua ekspresi mengevaluasi. true Jika ada ekspresifalse, ia kembalifalse.

Parameter

  • expressions: Sebuah array ekspresi untuk mengevaluasi.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan penggunaan $and operator untuk memeriksa apakah produk memenuhi beberapa kriteria.

Buat dokumen sampel

db.products.insertMany([ { _id: 1, name: "Laptop", price: 1200, inStock: true }, { _id: 2, name: "Mouse", price: 25, inStock: false }, { _id: 3, name: "Keyboard", price: 75, inStock: true } ]);

Contoh kueri

db.products.aggregate([ { $project: { name: 1, price: 1, inStock: 1, affordable: { $and: [ { $lt: ["$price", 100] }, { $eq: ["$inStock", true] } ] } } } ]);

Keluaran

[ { _id: 1, name: 'Laptop', price: 1200, inStock: true, affordable: false }, { _id: 2, name: 'Mouse', price: 25, inStock: false, affordable: false }, { _id: 3, name: 'Keyboard', price: 75, inStock: true, affordable: true } ]

Contoh kode

Untuk melihat contoh kode untuk menggunakan operator $and agregasi, pilih tab untuk bahasa yang ingin Anda gunakan:

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('products'); const result = await collection.aggregate([ { $project: { name: 1, price: 1, inStock: 1, affordable: { $and: [ { $lt: ["$price", 100] }, { $eq: ["$inStock", true] } ] } } } ]).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['products'] result = list(collection.aggregate([ { '$project': { 'name': 1, 'price': 1, 'inStock': 1, 'affordable': { '$and': [ { '$lt': ['$price', 100] }, { '$eq': ['$inStock', True] } ] } } } ])) print(result) client.close() example()