次の方法で共有


$meta

$metaプロジェクション演算子は、クエリの結果にメタデータを含めるために使用されます。 これは、テキスト検索スコアや他の計算値などのメタデータを出力ドキュメントに含める場合に便利です。

構文

$meta射影演算子を使用するための構文は次のとおりです。

db.collection.find({
    $text: {
        $search: < string >
    }
}, {
    field: {
        $meta: < metaDataKeyword >
    }
})

パラメーター

パラメーター Description
field メタデータが含まれる出力ドキュメント内のフィールドの名前。
metaDataKeyword テキスト検索スコアの textScore などの一般的なキーワードを含めるメタデータの種類。

例示

stores コレクションのこのサンプル ドキュメントについて考えてみましょう。

{
  "_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)

このクエリによって返される最初の 2 つの結果は次のとおりです。

[
  {
    _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" } は何も返しません。