$meta
投影运算符用于在查询结果中包含元数据。 它可用于在输出文档中包括元数据,例如文本搜索分数或其他计算值。
语法
使用 $meta
投影运算符的语法如下:
db.collection.find( {$text: { $search: <string> } },
{ field: { $meta: <metaDataKeyword> }
}
)
参数
参数 | 说明 |
---|---|
field |
输出文档中包含元数据的字段的名称。 |
metaDataKeyword |
包含常用关键字的元数据类型,如用于文本搜索分数的 textScore 。 |
例子
请考虑商店集合中的这个示例文档。
{
"_id": "34f462fe-5085-4a77-a3de-53f4117466bd",
"name": "Wide World Importers",
"location": {
"lat": -63.5435,
"lon": 77.7226
},
"staff": {
"totalStaff": {
"fullTime": 16,
"partTime": 16
}
},
"sales": {
"totalSales": 41481,
"salesByCategory": [
{
"categoryName": "Holiday Tableware",
"totalSales": 41481
}
]
},
"promotionEvents": [
{
"eventName": "Crazy Deal Days",
"promotionalDates": {
"startDate": {
"Year": 2023,
"Month": 11,
"Day": 13
},
"endDate": {
"Year": 2023,
"Month": 11,
"Day": 22
}
},
"discounts": [
{
"categoryName": "Gift Boxes",
"discountPercentage": 9
},
{
"categoryName": "Holiday Tableware",
"discountPercentage": 24
}
]
},
{
"eventName": "Incredible Savings Showcase",
"promotionalDates": {
"startDate": {
"Year": 2024,
"Month": 5,
"Day": 11
},
"endDate": {
"Year": 2024,
"Month": 5,
"Day": 20
}
},
"discounts": [
{
"categoryName": "Ribbons",
"discountPercentage": 15
},
{
"categoryName": "Gift Bags",
"discountPercentage": 25
}
]
}
],
"tag": [
"#ShopLocal",
"#FashionStore",
"#SeasonalSale",
"#FreeShipping",
"#MembershipDeals"
]
}
示例 1:包括文本搜索分数
在文本搜索查询的结果中包含文本搜索分数。
db.stores.createIndex({ "name": "text"});
db.stores.find(
{ $text: { $search: "Equipment Furniture Finds" } },
{ _id: 1, name: 1, score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } }).limit(2)
匹配文本搜索条件并包含 score
包含文本搜索分数的字段。
[
{
_id: 'cf1448e9-5493-49b5-95da-ab8a105b5240',
name: 'Tailwind Traders | Camera Market - Wolfmouth',
score: 4
},
{
_id: '4fd389af-4693-4c02-93cf-0d80ae8ace07',
name: 'Wide World Importers | Camera Collection - South Cordelia',
score: 4
}
]
限制
- 如果未使用索引,则 { $meta: "indexKey" } 不返回任何内容。
相关内容
- 查看有关 从 MongoDB 迁移到适用于 MongoDB 的 Azure Cosmos DB (vCore) 的选项。
- 详细了解 与 MongoDB 的功能兼容性。