【问题标题】:MongoDB: how to access numerical keys in the mapMongoDB:如何访问地图中的数字键
【发布时间】:2014-07-03 12:34:59
【问题描述】:

我的收藏中有以下文档

{ 
    "_id" : ObjectId("53732dc386d78e446c73fbb3"),
    "elig" : 18,
    "tags" : { 
        "6" : "49.6", 
        "9" : "657"
    }, 
    "book" : { 
        "type" : "100",
       "id" : "59598699"
    }
}

如果您注意到,标签是键值对,键为数字形式(基本上是 FIX 消息,标签和值对)

我需要将 tags.6 从 String ("49.6") 更新为 Float (49.6)。

当我尝试将 book.type 从“100”更新为 100 时,它起作用了。下面工作。

db.coll.find().forEach(function(data) {
    db.coll.update(
        {_id:data._id},
        {$set:{"book.type":parseFloat(data.book.type) }}
    );
})

但是对于tags.6,:

db.coll.find().forEach(function(data) {
    db.coll.update(
        {_id:data._id},
        {$set:{"tags.6":data.tags.6 }}
    );
})

报错

2014-05-15T08:23:40.161+0100 SyntaxError: Unexpected number

我不能有数字作为键吗?

请告诉我如何更新。

【问题讨论】:

    标签: mongodb subdocument


    【解决方案1】:

    问题在于您如何访问数据。使用data.tags["6"] 而不是data.tags.6。 IE。这样的更新会起作用:

    db.coll.update(
              {_id:data._id},
              {$set:{"tags.6":data.tags["6"] }}
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2017-01-07
      相关资源
      最近更新 更多