$eq
运算符用于匹配字段值等于指定值的文档。 $eq运算符根据查询谓词的完全匹配筛选文档,以检索具有特定值、对象和数组的文档。
语法
{
field: {
$eq: <value>
}
}
参数
参数 | 说明 |
---|---|
field |
要比较的字段 |
value |
要与之比较的值 |
例子
请考虑存储集合中的此示例文档。
{
"_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
"name": "Lakeshore Retail | DJ Equipment Stop - Port Cecile",
"location": {
"lat": 60.1441,
"lon": -141.5012
},
"staff": {
"totalStaff": {
"fullTime": 2,
"partTime": 0
}
},
"sales": {
"salesByCategory": [
{
"categoryName": "DJ Headphones",
"totalSales": 35921
}
],
"fullSales": 3700
},
"promotionEvents": [
{
"eventName": "Bargain Blitz Days",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 3,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 2,
"Day": 18
}
},
"discounts": [
{
"categoryName": "DJ Turntables",
"discountPercentage": 18
},
{
"categoryName": "DJ Mixers",
"discountPercentage": 15
}
]
}
],
"tag": [
"#ShopLocal",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
],
"company": "Lakeshore Retail",
"city": "Port Cecile",
"lastUpdated": {
"$date": "2024-12-11T10:21:58.274Z"
}
}
示例 1:对根级别字段使用$eq筛选器
查找名称为“布尔德创新”的商店 |Home Security Place - Ankundingburgh“,运行包含$eq谓词的查询,以匹配名称字段,并仅投影结果中的 ID 和名称字段。
db.stores.find({
"name": {
"$eq": "Boulder Innovations | Home Security Place - Ankundingburgh"
}
}, {
"name": 1
})
此查询返回以下结果:
{
"_id": "bda56164-954d-4f47-a230-ecf64b317b43",
"name": "Boulder Innovations | Home Security Place - Ankundingburgh"
}
示例 2:对嵌套字段使用$eq筛选器
若要查找总销售额为 37,015 美元的商店,请使用嵌套字段 sales.totalSales 字段上的点表示法使用 $eq 运算符运行查询。
db.stores.find({
"sales.totalSales": {
"$eq": 37015
}
}, {
"name": 1,
"sales.totalSales": 1
})
这会返回以下结果:
{
"_id": "bda56164-954d-4f47-a230-ecf64b317b43",
"name": "Boulder Innovations | Home Security Place - Ankundingburgh",
"sales": { "totalSales": 37015 }
}
示例 3:对数组中的单个项使用$eq
以下查询使用嵌套 promotionEvents.discounts 数组中各个项的相等谓词检索文档。
此查询在嵌套折扣数组中的任何一个对象上搜索相等匹配项
db.stores.find({
"promotionEvents.discounts": {
"$eq": {
"categoryName": "Alarm Systems",
"discountPercentage": 5
}
}
}, {
"name": 1
}, {
"limit": 2
})
此查询返回以下结果:
[
{
"_id": "ece5bf6c-3255-477e-bf2c-d577c82d6995",
"name": "Proseware, Inc. | Home Security Boutique - Schambergertown"
},
{
"_id": "7baa8fd8-113a-4b10-a7b9-2c116e976491",
"name": "Tailwind Traders | Home Security Pantry - Port Casper"
}
]
示例 4:使用$eq匹配整个数组
此查询基于 promotionEvents.discounts 数组中所有值的完全匹配来搜索文档。
db.stores.find({
"promotionEvents.discounts": {
"$eq": [{
"categoryName": "Alarm Systems",
"discountPercentage": 5
}, {
"categoryName": "Door Locks",
"discountPercentage": 12
}]
}
}, {
"name": 1
})
这会返回以下结果:
[
{
"_id": "aa9ad64c-29da-42f8-a1f0-30e03bf04a2d",
"name": "Boulder Innovations | Home Security Market - East Sheridanborough"
}
]
注释
对于整个数组的相等匹配,相等谓词中的指定值的顺序也必须完全匹配。