Ruby operations on MongoDB

Source: Internet
Author: User
Ruby connection to MongoDB

To connect to MongoDB in Ruby, you need to use the Mongo module. This module can be installed through the gems program that comes with Ruby.

$ gem update --system$ gem install mongo$ gem install bson_ext

The Mongo module provides the Mongo: connnection class to connect to MongoDB. If no specific database is specified, an instance with a MongoDB connection is created by default,

require 'mongo'conn = Mongo::Connection.newputs conn.class            # Mongo::Connectionputs conn.database_names   # ["admin", "local", ...]

If you need to specify the default database, you can specify it when creating an instance. If the specified database does not exist, MongoDB creates the database.

DB = Mongo: connection. New. dB ('blog ') dB. create_collection ('users') # create a collectionputs dB. class # Mongo: DB

Database Operations are involved, including basic creation, deletion, copy, and rename. The RENAME operation can be completed by copying and deleting a combination.

conn.copy_database('blog', 'blog-backup')conn.drop_database('blog-backup')

In MongoDB, tables are not defined. Instead, collection is used, which can be understood as a container. All records are stored in collection. What can be done for collection is the traditional CRUD operation, but it is more object-oriented. The Collection class of the Mongo module provides methods such as insert, drop, update, and find to operate collections. The following describes their usage.

Insert several records in the previously created collection named users. The record type in MongoDB is in JSON format. The format is as follows.

{"_ Id": objectid ("4d51eb216b6f45122c000001"), "username": "clovery", "password": "clovery"} # JSON format cannot be recognized in ruby, therefore, the ruby hash format is used to insert records. The Mongo module automatically converts the records to JSON format # inserts three records into users DB ['users']. insert ({"username" => "Andy", "password" => "12345"}) DB ['users']. insert ({"username" => "alien", "password" => "12345"}) DB ['users']. insert ({"username" => "angel", "password" => "12345"}) DB ['users']. count #3

You can use find_one and find to retrieve records. Find_one returns a bson: orderedhash data, similar to the ruby hash type. Find returns Mongo: cursor reference, which can be iterated to retrieve all data that meets the criteria.

db['users'].find_one   # {"_id"=>BSON::ObjectId('4d5246c26b6f451714000004'), "username"=>"andy", "password"=>"12345"}db['users'].find.each do |row|  print "#{row['username']} "end# andy alien angel

Update allows you to update existing records.

db['users'].update({'username' => 'andy'}, {'$set' => {'password' => 'andy'}})# {"_id"=>BSON::ObjectId('4d52499d6b6f451714000008'), "password"=>"andy", "username"=>"andy"}

Use remove to delete records in the collection. If no conditions are specified, all records in the collection will be deleted.

db['users'].remove({'username' => 'andy'}) db['users'].count # 2

Delete collection

db.drop_collection('users')

For details about how Ruby connects to mongdb, see MongoDB Ruby driver tutorial.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.