$filter - Amazon DocumentDB

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

$filter

$filterOperator di Amazon DocumentDB digunakan untuk menerapkan ekspresi filter ke setiap elemen array dan mengembalikan array yang hanya berisi elemen yang cocok dengan kondisi yang ditentukan. Operator ini berguna ketika Anda perlu melakukan operasi penyaringan kompleks pada bidang array dalam dokumen Anda.

Parameter

  • input: Bidang array untuk menyaring.

  • as: Nama variabel yang digunakan untuk setiap elemen input array dalam cond ekspresi.

  • cond: Ekspresi boolean yang menentukan apakah elemen tertentu harus disertakan dalam array output.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $filter operator untuk memproyeksikan pelanggan setiap pesanan dan membuat bidang array baru PaidItem berisi hanya item dari array item di mana harga lebih besar dari 15. Pada dasarnya, ini menyaring item setiap pesanan untuk memasukkan hanya produk yang harganya lebih dari 15.

Buat dokumen sampel

db.orders.insertMany([ { _id: 1, customer: "abc123", items: [ { name: "Product A", price: 10, qty: 2 }, { name: "Product B", price: 20, qty: 1 } ]}, { _id: 2, customer: "def456", items: [ { name: "Product C", price: 5, qty: 3 }, { name: "Product D", price: 15, qty: 4 } ]}, { _id: 3, customer: "ghi789", items: [ { name: "Product E", price: 8, qty: 3 }, { name: "Product F", price: 12, qty: 1 } ]} ]);

Contoh kueri

db.orders.aggregate([ { $project: { customer: 1, paidItems: { $filter: { input: "$items", as: "item", cond: { $gt: ["$$item.price", 15] } } } } } ]).pretty();

Keluaran

[ { _id: 1, customer: 'abc123', paidItems: [ { name: 'Product B', price: 20, qty: 1 } ] }, { _id: 2, customer: 'def456', paidItems: [] }, { _id: 3, customer: 'ghi789', paidItems: [] } ]

Contoh kode

Untuk melihat contoh kode untuk menggunakan $filter perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('test'); const collection = db.collection('orders'); const result = await collection.aggregate([ { $project: { customer: 1, paidItems: { $filter: { input: "$items", as: "item", cond: { $gt: ["$$item.price", 15] } } } } } ]).toArray(); console.log(JSON.stringify(result, null, 2)); } catch (error) { console.error('Error:', error); } finally { await client.close(); } } example();
Python
from pymongo import MongoClient from pprint import pprint def example(): uri = 'mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false' with MongoClient(uri) as client: db = client.test collection = db.orders result = list(collection.aggregate([ { '$project': { 'customer': 1, 'paidItems': { '$filter': { 'input': '$items', 'as': 'item', 'cond': { '$gt': ['$$item.price', 15] } } } } } ])) for doc in result: pprint(doc) example()