Mongoid push with upsert(Mongoid push with upsert)

我有模特用户:

class User field :username, type: String embeds_many :products end class Product field :name, type: String embedded_in :user end

我想进行单一操作:

插入用户 在用户已经存在的情况下更新用户(我可以轻松地使用upsert) 推动产品

这适用于upserting:

User.new(username: 'Hello').upsert

问题是这将删除嵌入式产品(未指定products属性)。

我可以问mongoid跳过将数组设置为空吗? 我可以问mongoid在产品阵列的最后推出新产品吗? 像这样的东西:

User.new(username: 'Hello').push(products: [Product.new(name: 'Screen')]).upsert

I've got model User:

class User field :username, type: String embeds_many :products end class Product field :name, type: String embedded_in :user end

I would like to have single operation that would:

insert the user update the user in case the user exists already (this i can easily do with upsert) push the products

This works for upserting:

User.new(username: 'Hello').upsert

The problem is that this will delete the embedded products (the products attribute is not specified).

Can I ask mongoid to skip setting array to empty? Can I ask mongoid to push new products at the end of products array? Something like this:

User.new(username: 'Hello').push(products: [Product.new(name: 'Screen')]).upsert

最满意答案

最后我通过手动编写以下查询结果:

User.mongo_client[:users].update_one({username: 'Hello'}, {"$set" => {first_name: 'Jim', last_name: 'Jones'}, "$pushAll" => [products: [{name: 'Screen'}, {name: 'Keyboard'}] }, upsert: true)

哪里:

$ set - 是我们想要为给定文档设置的参数 $ pushAll - 当你使用$ push时你只能指定一个元素,$ pushAll允许你追加多个元素(当你只指定一个元素时它会像$ push一样) upsert - 将在mongodb中执行插入/更新魔术

在第二个哈希中,您还可以指定$ inc,$ dec,$ pop,$ set等...这非常有用。

Finally I ended up by manually writing the following query:

User.mongo_client[:users].update_one({username: 'Hello'}, {"$set" => {first_name: 'Jim', last_name: 'Jones'}, "$pushAll" => [products: [{name: 'Screen'}, {name: 'Keyboard'}] }, upsert: true)

Where:

$set - are the params that we want to set for a given document $pushAll - when you use $push you can specify only one element, $pushAll allows you to append multiple elements (when you specify only one it will behave like $push) upsert - will do the insert/update magic in the mongodb

In the second hash you can also specify $inc, $dec, $pop, $set etc... which is quite useful.

更多推荐