How to query MongoDB directly from Ruby instead of using Mongoid?

前端 未结 7 448
刺人心
刺人心 2020-12-24 06:33

I am writing a migration for a Rails application that uses MongoDB and Mongoid. My migration currently uses my models that use Mongoid to query and update records, but the p

相关标签:
7条回答
  • 2020-12-24 07:18

    If you using mongoid 5(five) I would recommend using this.

    Item.collection.update_one({_id:  BSON::ObjectId('55512b7070722d22d3050000')}, '$set' => { 'category_name': 'Test' })
    

    The trick to this is the BSON::ObjectID. This is like in the mongo query if you want to search for a single id.

    db.items.update({ '_id': ObjectId("55512b7070722d22d3050000") }, { $set: {'category_name': 'Test' } })
    

    Above is the mongo version of the query. I found translating ruby code to mongo code is the hard part as there are a few pieces that can be a bit hard to find in the documentation.

    http://www.rubydoc.info/gems/mongo/Mongo%2FCollection%3Aupdate_one

    0 讨论(0)
提交回复
热议问题