本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$eq
Amazon DocumentDB 中的$eq運算子用於比對欄位值等於指定值的文件。此運算子常用於 find()方法,以擷取符合指定條件的文件。
參數
-
field :檢查等式條件的欄位。
-
value :要與 欄位比較的值。
範例 (MongoDB Shell)
下列範例示範 $eq運算子的使用情況,以尋找 name 欄位等於 的所有文件"Thai Curry Palace"。
建立範例文件
db.restaurants.insertMany([
{ name: "Thai Curry Palace", cuisine: "Thai", features: ["Private Dining"] },
{ name: "Italian Bistro", cuisine: "Italian", features: ["Outdoor Seating"] },
{ name: "Mexican Grill", cuisine: "Mexican", features: ["Takeout"] }
]);
查詢範例
db.restaurants.find({ name: { $eq: "Thai Curry Palace" } });
輸出
{ "_id" : ObjectId("68ee586f916df9d39f3d9414"), "name" : "Thai Curry Palace", "cuisine" : "Thai", "features" : [ "Private Dining" ] }
程式碼範例
若要檢視使用 $eq命令的程式碼範例,請選擇您要使用的語言標籤:
- Node.js
-
const { MongoClient } = require('mongodb');
async function findByName(name) {
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('restaurants');
const results = await collection.find({ name: { $eq: name } }).toArray();
console.log(results);
await client.close();
}
findByName("Thai Curry Palace");
- Python
-
from pymongo import MongoClient
def find_by_name(name):
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["restaurants"]
results = list(collection.find({ "name": { "$eq": name } }))
print(results)
client.close()
find_by_name("Thai Curry Palace")