Ruby Operation MongoDB (Advanced)-crud operation

Source: Internet
Author: User
Tags relational database table

The use of the MONGDB database is not a crud operation. What is crud, is creating documents, reading document information, updating documents, and deleting documents.

    1. Key-value Key-value pair tags

In MongoDB's Ruby driver, the Key_value key value appears multiple times. And sometimes there is a grammatical coincidence, depending on how you declare it in the Ruby version you're using.

In the document creation step, version 1.9 and later support the following syntax:

Document={name: "Tom", age:20}.

But if you're using a version of 2.2 or higher, you can wrap your key in double quotes. Such as:

document={"name": "Tom", "Age": 36}

If you need to use a MongoDB operator starting with "$", such as $set, $gte or $near, you must enclose it in double quotation marks. If you use 2.2 or a better ruby version, you can use the following notation:

Collection.update_one ({name: "Tom"},{"$set": {age:42}})

If you use an earlier version, use the Hashrocket notation

Collection.update_one ({name: "Tom"},{"$set" =>{age:42}})

Use strings and hashrockets to describe key-value pairs that are applicable in any version

Collection.update_one ({"Name" = "Tom"},{"$set" =>{"Age": 42})

2. Document creation-tabular creation of analogous relational databases

This is the first to tell the difference between a document creation in MongoDB and a table creation in a relational database. When inserting data into a collection in MongoDB, the document is created automatically, and the relational database table must be based on a predefined table structure. The benefit of MongoDB's mechanism is that it doesn't have to know the structure of the document beforehand. With better compatibility.

In MongoDB, after specifying a specific set name, we use Insert_one () and Insert_many () two methods to insert the document information into the collection. The insert operation returns a Mongo::operation::result object that contains the insertion information. In the 2.6 and later MongoDB versions, an exception is thrown if the insert fails because the Write command is used. In the 2.4 version of MongoDB, an exception is thrown only if the black and white is inserted and the result of the write is greater than or equal to 1 o'clock.

Client=mongo::client.new ([' 127.0.0.1:27017 '],:d atabase=> ' film ')

Result=client[:actors].insert_one ({:name=> "TK"})

RESULT.N #返回成功插入的文档数

Result=client[:actors].insert_many ([

{:name=> "April"},{:name=> ' Tom '}

])

Result.insert_count #此处返回2, inserting two documents

3. Decimal128 Type Number

In version 3.4, Decimal128 is a Bson data type that uses 128-bit floating-point values based on the decimal type to simulate precise fractional rounding, primarily for processing currency data, such as financial and tax calculations.

The following example inserts a document containing the DECIMAL128 type Price field in the inventory collection.

Client=mongo::client.new ([' 127.0.0.1:27017 '],:d atabse=> ' test ')

Price=bson::D ecimal128.new ("428.59")

Client[:inventory].insert_one ({"_id" =>1,

"Item" = "Moitor inch"

"Price" =>price

)

When the above statement is executed successfully, the following document is generated

{"_id": 1, "Item": "Inch Monitor", "Price": Numberdecimal ("428.59")}

You can also create a Decimal128 object from Ruby's BigDecimal object, or through Decimal128.from_string ().

Big_decimal=bigdecimal.new (428.79,5)

Price=bson::D ecimal128.new (Big_decimal)

Or

Price=bson::D ecimal128.from_string ("428.79")

4. Document Reading-analogy database query data

The Ruby driver type provides a smooth interface to the collection's queries through the Find method. The Find method also has multiple parameters available. The Query method is a lazy way for the server to execute. This means that the query is assigned only when the iteration is in the corresponding result, and a mongo::curor is returned. To find out all the collection of documents that satisfy the query rule, add the corresponding filter criteria through the Find method.

Client = Mongo::client.new ([' 127.0.0.1:27017 '],:d atabase= "film")

Client[:actors].find (:name=> "Tom"). Each do |document|

End

Query parameters, in order to increase the parameters of the query, a series of appropriate methods to string after the Find method. Mongo::collection::view is a newly generated and immutable object after each method call.

The following table is an example of the parameter list information that can be used when using a query method, as well as a corresponding method


Parameters Describe
Allow_patrial_results Used in shared cluster mode. If a fragment in the cluster goes down, the result of the query is obtained from the currently surviving fragments, so that it is possible to obtain only part of the result.
Batch_size (Integer) Sets the number of documents per batch that the cursor returns for each getmore operation
Commont (String) Comments for queries
Hint (Hash) Use index hint to optimize query speed when running queries
Limit (Integer) Limit the number of documents returned to the value provided
Max_scan (Integer) Set the maximum number of document scans if you want to perform a complete scan
No_cursor_timeout MongoDB automatically closes inactive cursors after a 10-minute interval, which allows the cursor to survive on the server permanently
Projection (Hash) Set what information to include in the results, and what information to reject. For example client[:actors].find.projection (: name=>1)
Read (Hash)

Only set read preferences for the current query

Client[:actors].find.read (: mode=>:secondary_preferred)


Show_disk_loc (Boolean) Let the result information contain the location information of the document
Skip (Integer) Skips a specified number of documents in the query results
Snapshot
Querying by using snapshot mode
Sort (Hash)

Determining collation of results

Client[:actors].find.sort (: name=>-1)

Query parameters for Attachments

4.1 Count

Gets the total number of documents returned by the document operation

Client=mongo::client.new ([' 127.0.0.1:27017 '],:d atabase= ' film ')

Client[:actors].find (:name=> "Tom"). Count

4.2 Distinct

Removes duplicate values from the result. Can be analogous to distinct operations in SQL

Client=mongo::client.new ([' 127.0.0.1:27017 '],:d atabase= ' film ')

Client[:actors].find.distinct (: Name)

4.3 tailable cursor

For the resulting collection, you may need to keep the tailable cursor open after the current cursor has traversed all the results. The following example shows how the tailable cursor is used.

Client=mongo::client.new ([' 127.0.0.1:27017 '],:d atabase=> ' film ')

Client[:actors].drop

Client[:actors,capped:true,size:512].create

Result=client[:actors].insert_many ([{:name=> "Tom"},{:name=> "Alex"}])

Enum=client[:actors].find ({},:cursor_type=>:tailable_wait). to_enum

While True

Doc=enum.text

End

4.4 Reading Preferences Read preference

This parameter sets the candidate member to which the query or corresponding command action should be sent in the replica set structure. It consists of a node that identifies a particular symbol, a hashes array named Tag_sets, and two time options (Local_threshold,server_selection_timeout).

Local_threshold: The upper value (in seconds) of the time lag window between the most recent server and the available servers that can send instruction operations. The default value is 0.015s or 15ms.

Server_selection_timeout: When the server is selected, the blocking time before the exception is thrown. The default is 30s, which is 30000ms.

For more information about the server selection algorithm, please refer to the following blog post.

The read preference parameter can be used as a parameter to a client connection or as a parameter to a command running on a database

#客户端连接时设定read The preference parameter, apply to all operations

Client = Mongo::client.new ([' 127.0.0.1:27017 '],read:{:mode=>:secondary,:tag_sets=>[{' dc ' = ' = ' NYC '}]})

#对于给定的命令设定读取首选项参数

Client.database.command ({:collstats=> ' test '},:read=>{:mode=>:secondary,:tag_sets=>[{' dc ' = ' NYC ' }]})

4.4.1 Mode parameter

The value of the pattern parameter contains five kinds, namely: Primary,:secondary,:p rimary_prefered,:secondary_prefered,:nearest. Please refer to the following blog post for details of the model meaning.

4.4.2 tag_sets Parameters

The Tag_sets parameter is a set of sorted labels that controls the election eligibility of the server when the server is elected. The tab set (T) that reads the preference is required to match the server's label set (s), and if T is a subset of S, the corresponding server tag set (s) matches the tab set (T) of the read preference.

For example, the Read Preferences tab set {DC: ' NY ', rack:2} matches an alternate server that owns the tag set {DC: ' NY ', rack:2,size: ' Large '}. An empty set of document tags can match any server, because an empty label set is a subset of any set of tags. This also means that the tag set parameter is [{}] When all servers are matched.


5. Document update-an update operation similar to a relational database

Document updates You can select individual updates or multiple updates together, or you can choose to use the findandmodify () command

5.1 Update_One

Client=mongo::client.new ([' 127.0.0.1:27017 '],:d atabase=> ' film ')

Actors=client[:actors]

#find后再modify

Result=actors.find (:name=> ' Alex '). Update_One ("$inc" =>{:p lays=>1})

Result.n

#直接update_one

Reslut=actors.update_one ({:name=> "Alex"},{"$inc" =>{:p alys=>1})

Result.n

5.2 Update_many

#find后再modify

Result =actors.find ([:label=> ' Hospital '). Update_many ("$inc" =>{:p lays=>1})

Result.modified_count

#直接update_many

Reslut=actors.update_many ({:label=> ' Hospital '},{"$inc" =>{:p Lays=>1}})

Result.modified_count

5.3 Replace_one

#find后再replace

Result =actors.find (:name=> ' Aphex Twin '). Replace_one (:name=> ' Richard ')

Result.modified_count

#直接replace_one

Result=actors.replace_one ({:name=> ' Aphex Twin '},{:name=> ' Richard ')

Result.modified_count

With the $findandmodify method for document updates and returns, you can use either of the Find_one_and_delete,find_one_and_replace,find_one_and_update three methods. You can wait until the update operation occurs before and after the corresponding document information.

5.4 Find_one_and_delete

Client=mongo::client.new ([' 127.0.0.1:27017 '],:d atabase=> ' film ')

Actors=client[:actors]

Actors.find (:name=> ' Jose James '). Find_one_and_delete

5.5 Find_one_and_replace

Doc=actors.find (: Name=>jose James '). Find_one_and_replace (:name=> ' Jose ')

Doc

Doc=actors.find_one_and_replace ({:name=> ' Jose James '},{:name=> ' Jose ')

Doc

Doc=actors.find (:name=> ' Jose James '). Find_one_and_replace ({:name=> ' Jose '},:return_document=>:after)

Doc

5.6 Find_one_and_update

Doc=actors.find (: name= ' Jose James '). Find_one_and_update (' $set ' =>{:name=> ' Jose ')

Doc

Doc=actors.find_one_and_update ({:name=> ' Jose James '},{' $set ' =>{:name=> ' Jose ')}

Doc

5.7 Find_one_and_replace

Doc=actors.find (:name=> ' Jose James '). Find_one_and_replace ({' $set ' =>{:name=> ' Jose '}},:return_document= >:after)

Doc

Doc=actors.find_one_and_replace ({:name=> ' Jose James '},{' $set ' =>{:name=> ' Jose '}},return_document=>: After

Doc

6 Document deletion operation deleting

6.1 Delete_one Single Delete

Client=mongo::client.new ([' 127.0.0.1:27017 '],:d atabase=> ' film ')

Actors=client[:actors]

#find后再删除

Result=actors.find (:name=> ' Bob '). Delete_one

Result.deleted_count

#直接delete

Result=actors.delete_one ({:name=> ' Bob '})

Result.deleted_count

6.2 Delete_many Multiple deletions

Result=actors.find (:label=> ' Mute '). Delete_many

Result.deleted_count

Result=actors.delete_many ({:label=> ' Mute '})

Result.deleted_count


At this point, Ruby operates the crud operations of MongoDB. This section is the base part of the database.

This article from "Techfuture" blog, declined reprint!

Ruby Operation MongoDB (Advanced)-crud operation

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.