Condividi tramite


$objectToArray (operatore di espressione di matrice)

SI APPLICA A: MongoDB vCore

L'operatore $objectToArray viene usato per convertire un documento ( ovvero un oggetto ) in una matrice di coppie chiave-valore. Questo operatore può essere utile quando è necessario modificare o analizzare la struttura di un documento in un formato di matrice più flessibile.

Sintassi

La sintassi per l'operatore $objectToArray è la seguente:

{
  $objectToArray: <object>
}

Parametri

Descrizione
<object> Documento (o oggetto) da convertire in una matrice di coppie chiave-valore.

Si esaminerà ora l'utilizzo con il codice JSON di esempio seguente.

{
  "_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"
  ]
}

Ecco alcuni esempi di come usare l'operatore $objectToArray con il codice JSON di esempio fornito.

Esempio 1: Conversione di un campo geospaziale in una matrice

La pipeline di aggregazione seguente converte il location campo del store documento in una matrice di coppie chiave-valore.

db.stores.aggregate([ 
    {
        $project: {
          locationArray: { $objectToArray: "$location" }
        }
    },
    // Limit the result to the first 3 documents
    { $limit: 3 }
])

Questa query restituirà il documento seguente.

[
  {
    "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
    "locationArray": [ { "k": "lat", "v": -85.0867 }, { "k": "lon", "v": -165.3524 } ]
  },
  {
    "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
    "locationArray": [ { "k": "lat", "v": -22.5751 }, { "k": "lon", "v": -12.4458 } ]
  },
  {
    "_id": "57cc4095-77d9-4345-af20-f8ead9ef0197",
    "locationArray": [ { "k": "lat", "v": -41.287 }, { "k": "lon", "v": -76.0176 } ]
  }
]

Esempio 2: Conversione di un documento secondario in una matrice

In questo esempio il totalStaff campo del staff documento viene convertito in una matrice di coppie chiave-valore.

db.stores.aggregate([
    {
      $project: {
        staffArray: { $objectToArray: "$staff.totalStaff" }
      }
    },
    // Limit the result to the first 3 documents
    { $limit: 3 }
])

Questa query restituirà il documento seguente.

[
  {
    "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
    "staffArray": [ { "k": "fullTime", "v": 15 }, { "k": "partTime", "v": 9 } ]
  },
  {
    "_id": "8345de34-73ec-4a99-9cb6-a81f7b145c34",
    "staffArray": [ { "k": "fullTime", "v": 12 }, { "k": "partTime", "v": 14 } ]
  },
  {
    "_id": "57cc4095-77d9-4345-af20-f8ead9ef0197",
    "staffArray": [ { "k": "fullTime", "v": 4 }, { "k": "partTime", "v": 8 } ]
  }
]

Esempio 3: Conversione di un campo datetime in una matrice

Questa pipeline converte il promotionalDates campo per ogni evento promozionale in una matrice di coppie chiave-valore.

db.stores.aggregate([
    {
      $project: {
        promotionEvents: {
          $map: {
            input: "$promotionEvents",
            as: "event",
            in: {
              eventName: "$$event.eventName",
              promotionalDatesArray: { $objectToArray: "$$event.promotionalDates" }
            }
          }
        }
      }
    },
    // Limit the result to the first document
    { $limit: 1 }
])

Questa query restituirà il documento seguente.

[
  {
    "_id": "649626c9-eda1-46c0-a27f-dcee19d97f41",
    "promotionEvents": [
      {
        "eventName": "Markdown Mayhem",
        "promotionalDatesArray": [
          { "k": "startDate", "v": { "Year": 2024, "Month": 3, "Day": 24 } },
          { "k": "endDate", "v": { "Year": 2024, "Month": 4, "Day": 3 } }
        ]
      },
      {
        "eventName": "Spectacular Savings Showcase",
        "promotionalDatesArray": [
          { "k": "startDate", "v": { "Year": 2024, "Month": 6, "Day": 22 } },
          { "k": "endDate", "v": { "Year": 2024, "Month": 7, "Day": 1 } }
        ]
      }
    ]
  }
]