草庐IT

mongodb - mgo 的 insert 方法是否将字段名称从大写更改为小写?

coder 2023-06-29 原文

  1. 当使用 mgoGo struct 类型的对象作为文档插入到 MongoDB 数据库的集合中时,字段名称是否自动从大写更改为小写?

  2. 如果是,为什么mgo的插入方法会那样做?

谢谢。


这是我的 Go 程序,它使用 mgo 在 MongoDB 服务器中执行插入和查询操作

package main

import (
    "fmt"
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type Record struct {
    Dimension_id  int
    Attribute string
    Hour string
    Frequency_count int
}

func main(){

    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    }
    defer session.Close()

    c := session.DB("TVFS").C("c20160712")

    // insert
    doc := Record{2, "good", "20160712_06", 100}
    err = c.Insert(&doc)
    if err != nil {
        panic(err)
    }

    // query
    result := Record{}
    err = c.Find(bson.M{"Dimension_id": 2, "Attribute": "good", "Hour": "20160712_06" }).One(&result) // no matching document
    // err = c.Find(bson.M{"dimension_id": 2, "attribute": "good", "hour": "20160712_06" }).One(&result) // one matching document
    if err != nil {
        panic(err)
    }
    fmt.Printf("count:%d\n", result.Frequency_count)

}

运行其编译程序的输出指出

$ ./minimal-example 
panic: not found

goroutine 1 [running]:
panic(0x61d500, 0xc82000a880)
    /usr/local/go/src/runtime/panic.go:481 +0x3e6
main.main()
    /home/t/program_files/mywork/go/src/tvfs/mongodb/minimal-example.go:38 +0x701

通过shell连接MongoDB服务器,发现插入文档中的字段名已经从首字母大写变为首字母小写

$ mongo
MongoDB shell version: 3.2.8
connecting to: test
Server has startup warnings: 
2016-08-04T11:58:21.138-0400 I CONTROL  [initandlisten] 
2016-08-04T11:58:21.138-0400 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2016-08-04T11:58:21.138-0400 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-08-04T11:58:21.138-0400 I CONTROL  [initandlisten] 
2016-08-04T11:58:21.139-0400 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2016-08-04T11:58:21.139-0400 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-08-04T11:58:21.139-0400 I CONTROL  [initandlisten] 
> show dbs
TVFS   0.000GB
local  0.000GB
> use TVFS
switched to db TVFS
> show collections
c20160712
> db.c20160712.find()
{ "_id" : ObjectId("57a3978491c3b3a393e9be2d"), "dimension_id" : 2, "attribute" : "good", "hour" : "20160712_06", "frequency_count" : 100 }

所以在我的Go程序中,我改变了

    err = c.Find(bson.M{"Dimension_id": 2, "Attribute": "good", "Hour": "20160712_06" }).One(&result) // no matching document

成为

    err = c.Find(bson.M{"dimension_id": 2, "attribute": "good", "hour": "20160712_06" }).One(&result) // one matching document

并且有一个匹配的文档

$ ./minimal-example 
count:100

最佳答案

字段名称根据 mgo/bson documentation 小写:

The lowercased field name is used as the key for each exported field, but this behavior may be changed using the respective field tag.

使用 bson 字段标记来覆盖 mgo/bson 对结构名称的处理。以下是匹配结构字段名称所需的标记:

type Record struct {
   Dimension_id  int     `bson:"Dimension_id"`
   Attribute string      `bson:"Attribute"`
   Hour string           `bson:"Hour"`
   Frequency_count int   `bson:"Frequency_count"`
}

关于mongodb - mgo 的 insert 方法是否将字段名称从大写更改为小写?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38778360/

有关mongodb - mgo 的 insert 方法是否将字段名称从大写更改为小写?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  4. ruby - Facter::Util::Uptime:Module 的未定义方法 get_uptime (NoMethodError) - 2

    我正在尝试设置一个puppet节点,但ruby​​gems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由ruby​​gems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby

  5. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  6. Ruby 方法() 方法 - 2

    我想了解Ruby方法methods()是如何工作的。我尝试使用“ruby方法”在Google上搜索,但这不是我需要的。我也看过ruby​​-doc.org,但我没有找到这种方法。你能详细解释一下它是如何工作的或者给我一个链接吗?更新我用methods()方法做了实验,得到了这样的结果:'labrat'代码classFirstdeffirst_instance_mymethodenddefself.first_class_mymethodendendclassSecond使用类#returnsavailablemethodslistforclassandancestorsputsSeco

  7. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  8. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  9. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  10. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

随机推荐