Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an upsert / push with mongoid / moped

I'm using Mongoid (v3) to access MongoDB, and want to perform this action:

db.sessionlogs.update( 
    {sessionid: '12345'}, /* selection criteria */
    {'$push':{rows: "new set of data"}},  /* modification */
    true /* upsert */
);

This works fine in the mongo shell. It's also exactly what I want since it's a single atomic operation which is important to me as I'm going to be calling it a lot. I don't want to have to do two operations -- a fetch and then an update. I've tried a bunch of things through mongoid, but can't get it to work.

How can I get MongoID out of the way and just send this command to MongoDB? I'm guessing there's some way to do this at the Moped level, but the documentation of that library is basically non-existent.

like image 210
Leopd Avatar asked Jul 18 '12 17:07

Leopd


1 Answers

[Answer found while writing the question...]

criteria = Sessionlogs.collection.find(:sessionid => sessionid)
criteria.upsert("$push" => {"rows" => datarow})
like image 162
Leopd Avatar answered Oct 17 '22 05:10

Leopd