本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$eq
$eq聚合运算符比较两个值,true如果它们相等,则返回,否则返回false。
参数
-
expression1:要比较的第一个值。
-
expression2: 第二个要比较的值。
示例(MongoDB 外壳)
以下示例演示如何使用$eq运算符来检查产品数量是否与目标值匹配。
创建示例文档
db.inventory.insertMany([
{ _id: 1, item: "Widget", qty: 50, target: 50 },
{ _id: 2, item: "Gadget", qty: 30, target: 50 },
{ _id: 3, item: "Tool", qty: 50, target: 40 }
]);
查询示例
db.inventory.aggregate([
{
$project: {
item: 1,
qty: 1,
target: 1,
meetsTarget: { $eq: ["$qty", "$target"] }
}
}
]);
输出
[
{ _id: 1, item: 'Widget', qty: 50, target: 50, meetsTarget: true },
{ _id: 2, item: 'Gadget', qty: 30, target: 50, meetsTarget: false },
{ _id: 3, item: 'Tool', qty: 50, target: 40, meetsTarget: false }
]
代码示例
要查看使用$eq聚合运算符的代码示例,请选择要使用的语言的选项卡:
- 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('inventory');
const result = await collection.aggregate([
{
$project: {
item: 1,
qty: 1,
target: 1,
meetsTarget: { $eq: ["$qty", "$target"] }
}
}
]).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['inventory']
result = list(collection.aggregate([
{
'$project': {
'item': 1,
'qty': 1,
'target': 1,
'meetsTarget': { '$eq': ['$qty', '$target'] }
}
}
]))
print(result)
client.close()
example()