本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$eq
Amazon DocumentDB 中的$eq运算符用于匹配字段值等于指定值的文档。该运算符通常用于检索符合指定条件的文档find()的方法。
参数
-
field:要检查相等条件的字段。
-
value:要与字段进行比较的值。
示例(MongoDB 外壳)
以下示例演示如何使用$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")