1

I am trying to update the mongodb embedded collection using the $ positional operator from ruby mongoid, but it is not working. Below the mongoid query

Viewcounter.collection.update({:item_id=>BSON::ObjectId('yyyy'),'viewinfos.remote_ip' => 'xxxx'},{'$inc' => {'viewinfos.$.viewcount' => 1}})

After some more digging i found that no mongodb queries works with mongoid update.including below simple query

Item.collection.update({'_id' =>BSON::ObjectId('sss')},{:isused => false})

has anyone got a better way of doing the positional operator queries with mongoid?

EDIT

But as per the mongodb official ruby driver documentation, this should work. below the excerpt

coll.update({"_id" => doc["_id"]}, {"$set" => {"name" => "MongoDB Ruby"}})
RameshVel
  • 64,778
  • 30
  • 169
  • 213

1 Answers1

4

The general idea is you would drop down to the ruby driver (through the collection) and do it like this:

Viewcounter.collection.update({"viewinfos.remote_ip" => "xxxx"}, {:$inc => {"viewinfos.$.viewcount" => 1}})
Tyler Brock
  • 29,626
  • 15
  • 79
  • 79
  • Your approach was fine. But is there any other way to include the parent id along with $ positional operator. because i need to update a embedded coll based on both parent id and the embedded field.. – RameshVel Dec 21 '11 at 07:09
  • You can throw extra conditionals in the query document that select the parent you want. (i think that is what you are asking about) Otherwise you might need to do it on the client side programmatically. – Tyler Brock Dec 21 '11 at 16:35