How to remove additional keys added while inserting nested structure in mongodb

王林
Release: 2024-02-09 12:06:18
forward
1064 people have browsed it

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

php editor Apple brings you an article on how to remove additional keys added when inserting nested structures in mongodb. When using mongodb to store data, sometimes we add some additional keys to the nested structure to facilitate query and operation. But how do we remove these additional keys when we no longer need them? This article will provide you a simple and effective method to help you easily remove the additional keys added when inserting nested structures in mongodb. Let’s take a look!

Question content

Assume this is my structure definition,

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
}
Copy after login

When content is stored in MongoDB, it is stored as

{
  "_id": ObjectID,
  "partialcontent": {
    "key": "...",
    "value": "..."
  }
}
Copy after login

But JSON unmarshalling returns

{
  "_id": ObjectID,
  "key": "...",
  "value": "..."
}
Copy after login

How to remove additional keys partialcontent in MongoDB?

Workaround

First, you need to export the structure fields, otherwise the driver will skip them.

If you do not want to embed the document in MongoDB, use the ,inline bson tag option:

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"`
}
Copy after login

Insert the value:

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

This document will be generated in MongoDB:

{ "_id" : "abc", "key" : "k1", "value" : "v1" }
Copy after login

The above is the detailed content of How to remove additional keys added while inserting nested structure in mongodb. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template