在 MongoDB 中更新而无需首先拉取 Mongoid 对象?

Updating in MongoDB without first having to pull a Mongoid object?

执行查询时,我可以通过 Mongoid:

product_obj = Product.where(
                            _id: "58f876f683c336eec88e9db5"
                           ).first # => #<Product _id: 58f876f683c336eec88e9db5, created_at: nil, updated_at: nil, sku: "123", name: "Some text", ...)

或者我可以绕过它:

product_hsh = Product.collection.find( {
                                         _id: BSON::ObjectId.from_string("58f876f683c336eec88e9db5")
                                       }, {
                                         projection: {
                                          _id: 1,
                                          name: 1
                                        }
                                      } ).first # => {"_id"=>BSON::ObjectId('58f876f683c336eec88e9db5'), "name"=>"Some text"} 

我更喜欢规避,因为它性能更好;我可以限制在响应中获取哪些字段。

但是,我的问题是如何进一步处理退回的产品。响应是一个散列,而不是一个对象,所以如果我必须更新它,我无论如何都需要通过 Mongoid 拉它,因此性能提升就消失了:

Product.find(product_hsh["_id"]).update_attribute(:name, "Some other text")

我的问题是:如何在不先拉取 Mongoid 对象的情况下进行更新?

您根本不需要 pull/fetch。您可以直接发送 $set 命令:

Product.where(id: product_hsh["_id"]).update_all(name: "Some other text")