次の方法で共有


$elemMatch (配列クエリ)

適用対象: MongoDB 仮想コア

$elemMatch演算子は、配列フィールドを含むドキュメントと、指定されたすべてのクエリ条件に一致する少なくとも 1 つの要素を照合するために使用されます。 この演算子は、指定した要素を持つ配列ドキュメントを検索する必要がある場合に特に便利です。

構文

$elemMatch演算子の基本的な構文は次のとおりです。

db.collection.find({ <field>: { $elemMatch: { <query1>, <query2>, ... } } })

パラメーター

説明
field クエリを実行する配列を含むドキュメント内のフィールド。
query 配列内の少なくとも 1 つの要素が満たす必要がある条件。

データセットからのサンプル json の使用方法 stores 理解しましょう。

[
  {
    "_id": "91de5201-8194-44bf-848f-674e8df8bf5e",
    "name": "Adatum Corporation",
    "promotionEvents": [
      {
        "discounts": [
          { "categoryName": "DJ Cases", "discountPercentage": 6 },
          { "categoryName": "DJ Mixers", "discountPercentage": 14 }
        ]
      },
      {
        "discounts": [
          { "categoryName": "DJ Headphones", "discountPercentage": 19 },
          { "categoryName": "DJ Speakers", "discountPercentage": 13 }
        ]
      },
      {
        "discounts": [
          { "categoryName": "DJ Lighting", "discountPercentage": 12 },
          { "categoryName": "DJ Accessories", "discountPercentage": 6 }
        ]
      }
    ]
  }
]

例 1: 要素のリスト内の特定の要素の配列を検索する

次の使用例は、 stores コレクションの最初の 2 つのドキュメントのうち、カテゴリ名が "DJ Lighting" の割引が少なくとも 1 つ存在するドキュメントを、 promotionEvents 配列で検索します。 クエリは、これらのドキュメントの _id フィールドと promotionEvents.discounts フィールドのみを返します。

db.stores.find(  {"promotionEvents.discounts":{$elemMatch:{"categoryName":"DJ Lighting"}}}
                ,{ _id: 1, "promotionEvents.discounts": 1 }).limit(2)

次のドキュメントが返されます。

{
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "promotionEvents": [
      {
        "discounts": [
          {
            "categoryName": "DJ Turntables",
            "discountPercentage": 18
          },
          {
            "categoryName": "DJ Mixers",
            "discountPercentage": 15
          }
        ]
      },
      {
        "discounts": [
          {
            "categoryName": "DJ Lighting",
            "discountPercentage": 14
          },
          {
            "categoryName": "DJ Cases",
            "discountPercentage": 20
          }
        ]
      }
    ]
  },
  {
    "_id": "91de5201-8194-44bf-848f-674e8df8bf5e",
    "promotionEvents": [
      {
        "discounts": [
          {
            "categoryName": "DJ Cases",
            "discountPercentage": 6
          },
          {
            "categoryName": "DJ Mixers",
            "discountPercentage": 14
          }
        ]
      },
      {
        "discounts": [
          {
            "categoryName": "DJ Headphones",
            "discountPercentage": 19
          },
          {
            "categoryName": "DJ Speakers",
            "discountPercentage": 13
          }
        ]
      },
      {
        "discounts": [
          {
            "categoryName": "DJ Lighting",
            "discountPercentage": 12
          },
          {
            "categoryName": "DJ Accessories",
            "discountPercentage": 6
          }
        ]
      }
    ]
}