Question

I am looking to add to multiple sets, and at the same time update the updated_at timestamp (touch). I could do this using the mongo driver:

db.mycollection.update({"_id": ObjectId("911")},
 {
  $addToSet: { "hashtags": {$each: ["#test1", "#test5"]}, "new_hash": {$each: ["test9"]} },
  $set: {"updated": "current time 3"}
 }
 )

How can I do this using mongoid in a rails app, in a single update query. Right now, I need to do 3 writes using mongoid:

my_object.add_to_set("hashtags", ["#test1", "#test5"])
my_object.add_to_set("new_hash", ["test9"])
my_object.touch
Was it helpful?

Solution

You must use Moped, the Mongoid Driver (docs here: http://mongoid.org/en/moped/docs/driver.html).

something like this should do the trick:

my_query = {
 '$addToSet' => { "hashtags" => {'$each' => ["#test1", "#test5"]}, "new_hash" => {'$each' => ["test9"]} },
 '$set' => {"ts" => Time.now}
}
MyClass.collection.find('_id' => my_object.id).update(my_query)

OTHER TIPS

I am not sure, but if you do this:

my_object.hashtags += ["#test1", "#test5"]
my_object.new_hash += ["test9"]
my_object.save

I think that it only writes one time and the updated_at field is updated automatically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top