【问题标题】:I could not push an new data into array when use upsert使用 upsert 时我无法将新数据推送到数组中
【发布时间】:2015-06-11 05:55:38
【问题描述】:

使用 upsert 时我无法将 new_data 推送到数组中

如何使用 upsert 插入/更新一个文档?

history 是一个数组。

顺便说一句,宝石mongo 的数据'似乎远不如PythonJavascript 受欢迎。

gemmongo是不是比其他语言功能少,bug多?

ArgumentError:参数数量错误(1..2 为 3)

[64] pry(#<Scoot>)> @db.data_collection.find({_id: data[:_id]}).update_one(
[64] pry(#<Scoot>)*   {data: data,
[64] pry(#<Scoot>)*     from: from_city,
[64] pry(#<Scoot>)*   },
[64] pry(#<Scoot>)*   {:$push => { "history" => new_data }},
[64] pry(#<Scoot>)*   :upsert => true,
[64] pry(#<Scoot>)*   :safe => true
[64] pry(#<Scoot>)* )
ArgumentError: wrong number of arguments (3 for 1..2)

Mongo::Error::OperationFailure: '$push' 中的美元 ($) 前缀字段 '$push' 对存储无效。 (52)

@db.data_collection.find({_id: data[:_id]}).update_one(
  {data: data,
    from: from_city,
    :$push => { "history" => new_data },
    },
  :upsert => true,
  :safe => true
)

更新 GEM MONGO 2.0.4

collection.find({_id: data[:_id]}).update_one(
  {
    "$set" => {
      "city" => from_city
    },
    "$push": => { "history" => new_data }
  },
  :upsert => true
)

错误

SyntaxError: unexpected tSTRING_DEND, expecting end-of-input
[105] pry(#<Scoot>)> :upsert => true
SyntaxError: unexpected =>, expecting end-of-input
:upsert => true
          ^
[105] pry(#<Scoot>)> )
SyntaxError: unexpected ')', expecting end-of-input

【问题讨论】:

    标签: ruby mongodb


    【解决方案1】:

    假设您在这里使用的是 2.X 驱动程序系列。主要问题是不支持:$push 语法,所以你用不同的方式编写它。此外,:safe 早已被弃用,无论您从哪里读到它。另外,当您想设置对象的特定字段时,您可以使用"$set

    @db.data_collection.find({ _id: data[:_id]}).update_one({
          "$set" => { 
              "data" => data,
              "city" => from_city
          },
          "$push" => { "history" => new_data }
      },
      :upsert => true
    ) 
    

    查看update_one的文档

    【讨论】:

    • 您的解决方案仍然无效。请看我的更新谢谢,
    • @user3675188 这是一个错字。删除 $push 后的 :
    • 非常感谢,您的解释比糟糕的正式文档更有帮助。
    • @user3675188 我承认 ruby​​ 文档是最糟糕的文档之一。核心 MongoDB 文档有更好的示例,只需注意在需要时将语法更改为 ruby​​ 规范。另请注意,在 2.X 驱动程序系列(以及大多数其他语言的最新驱动程序)中,实际选项和方法是使用下面的“批量 API”建模的。所以最相关的是那些调用方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多