首頁  >  文章  >  後端開發  >  如何刪除在 mongodb 中插入巢狀結構時所新增的附加鍵

如何刪除在 mongodb 中插入巢狀結構時所新增的附加鍵

王林
王林轉載
2024-02-09 12:06:181028瀏覽

如何删除在 mongodb 中插入嵌套结构时添加的附加键

php小編蘋果為您帶來一篇關於如何刪除在mongodb中插入巢狀結構時所新增的附加鍵的文章。在使用mongodb儲存資料時,有時候我們會為了方便查詢和操作而在巢狀結構中加入一些附加鍵。但是,當我們不再需要這些附加鍵時,如何刪除它們呢?本文將為您提供一種簡單有效的方法,幫助您輕鬆刪除在mongodb中插入巢狀結構時所新增的附加鍵。讓我們一起來看看吧!

問題內容

假設這是我的結構定義,

type partialContent struct {
  key   string   `json:"key" bson"key"`
  value string   `json:"value" bson:"value"`
}

type content struct {
  id string `json:"id" bson:"_id,omitempty"`
  partialContent
}

在 MongoDB 中儲存內容時,它被儲存為

{
  "_id": ObjectID,
  "partialcontent": {
    "key": "...",
    "value": "..."
  }
}

但是 JSON 解組回傳

{
  "_id": ObjectID,
  "key": "...",
  "value": "..."
}

如何刪除 MongoDB 中的附加鍵 partialcontent

解決方法

首先,您需要匯出結構字段,否則驅動程式將跳過這些字段。

如果您不想在 MongoDB 中嵌入文檔,請使用 ,inline bson 標籤選項:

type PartialContent struct {
    Key   string `json:"key" bson"key"`
    Value string `json:"value" bson:"value"`
}

type Content struct {
    ID             string `json:"id" bson:"_id,omitempty"`
    PartialContent `bson:",inline"`
}

插入該值:

v := Content{
    ID: "abc",
    PartialContent: PartialContent{
        Key:   "k1",
        Value: "v1",
    },
}

將在 MongoDB 中產生此文件:

{ "_id" : "abc", "key" : "k1", "value" : "v1" }

以上是如何刪除在 mongodb 中插入巢狀結構時所新增的附加鍵的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除