$ (projection)

APPLIES TO: MongoDB vCore

The $ operator is used for array projection, allowing users to extract first element from an array matching the query condition.

Syntax

The syntax for using the $ projection operator is as follows:

db.collection.find({}
    ,{
        "projection_field": {
            "$": 1
            }
    }
)

Parameters

Description
projection_field The name of the array field from which specific element needs to be projected.

Example

Let's understand the usage with sample json from stores dataset.

{
  "_id": "d3c9df51-41bd-4b4e-a26b-b038d9cf8b45",
  "name": "Lakeshore Retail",
  "location": {
    "lat": -67.7571,
    "lon": 97.2505
  },
  "sales": {
    "totalSales": 149849,
    "salesByCategory": [
      {
        "categoryName": "DJ Speakers",
        "totalSales": 36972
      },
      {
        "categoryName": "DJ Headphones",
        "totalSales": 12877
      },
      {
        "categoryName": "Music Accessories",
        "totalSales": 40000
      },
      {
        "categoryName": "DJ Accessories",
        "totalSales": 60000
      }
    ]
  },
  "tag": [
    "#ShopLocal",
    "#FashionStore",
    "#SeasonalSale",
    "#FreeShipping",
    "#MembershipDeals"
  ]
}

Example 1: Projects first element of an array, matching the condition

The example returns the first element within the salesByCategory array, for DJ equipment with totalSales greater than 35000.

db.stores.find(
     { "sales.salesByCategory": {
                                  $elemMatch: {
                                        "categoryName": { $regex: "^DJ" }
                                      }
                                  }
    ,"sales.salesByCategory.totalSales": {$gt: 35000} }
    ,{"sales.salesByCategory.$":1}
).limit(2)

This query returns two matching documents as enforced by limit, with only the first element from that array.

  {
    "_id": "d3c9df51-41bd-4b4e-a26b-b038d9cf8b45",
    "sales": {
      "salesByCategory": [
        {
          "categoryName": "DJ Speakers",
          "totalSales": 36972
        }
      ]
    }
  },
  {
    "_id": "7954bd5c-9ac2-4c10-bb7a-2b79bd0963c5",
    "sales": {
      "salesByCategory": [
        {
          "categoryName": "DJ Headphones",
          "totalSales": 35911
        }
      ]
    }
  }

Limitations

  • Only one positional $ operator can appear in the projection document.
  • Only one array field should appear in the query document. More array fields in the query document might lead to undefined behavior.