MongoDB Learning Notes-06 database commands, pinned sets, Gridfs, JavaScript scripts

Source: Internet
Author: User
Tags mongodb server mongodb support

Describes some of the advanced features of MongoDB support:

Database commands

Fixed-size collections

Gridfs Storing large files

MongoDB Support Database command for server-side JavaScript

the principle of the command

The commands in MongoDB are actually implemented as a special type of query that is executed against the $cmd collection. RunCommand simply accepts the command document and executes the equivalent query.

>db.runcommand ({"Drop": "Test"})

The above command is equivalent to the following query:

>db. $cmd. FindOne ({"Drop": "Test"})

When the MongoDB server gets a request to query the $cmd collection, it starts a set of special logic to handle, rather than handing it over to the normal query code.

Access to some commands requires administrator privileges and must be run in the admin database. Otherwise, you will get an "Access Denied" error.

List of common commands

You can use Db.listcommand () to list all the commands that MongoDB supports. The frequently used commands are as follows:

Buildinfo: Returns the version number of the MongoDB server and the host's operating system and other information

>db.runcommand ({"Buildinfo": 1})

Collstats: Returns statistics for the specified collection, including data size, allocated storage space, and index size.

>db.runcommand ({"Collstats": "CollectionName"})

Distinct: Returns all the different values of the specified key in the specified collection that satisfy the query criteria

>db.runcommand ({"distinct": "CollectionName", "Key": "KeyName", "Query": query})

Drop: Delete the specified collection

>db.runcommand ({"Drop": "CollectionName"})

Dropdatabase: Delete db point to the database,

>db.runcommand ({"Dropdatabase": 1})

Dropindexes: Deletes the index of the specified name in the collection, when the name is * Delete all.

>db.runcommand ({"dropindexes": "CollectionName", "index": "IndexName"})

Findandmodify: Returning the updated document

>db.runcommand ({"findandmodify": "CollectionName", "Query": Query, "sort": Sort, "Update": Update})

GetLastError: Returns an error message or other status information for the last operation performed on this collection.

>db.runcommand ({"GetLastError": 1})

IsMaster: Detects if this server is the primary server

>db.runcommand ({"IsMaster": 1})

Listcommands: Returns all commands and related information that can be run on the server

>db.runcommand ({"Listcommands": 1})

ListDatabases: Lists all databases on the server, similar to show DBS results, for administrator-specific

>db.runcommand ({"ListDatabases": 1})

Ping: detects that the server connection is healthy

>db.runcommand ({"Ping": 1})

Renamecollection: Renaming a collection

>db.runcommand ({"Renamecollection": A, "to": B})

RepairDatabase: Repairs and compresses the current database, DB points to the database

>db.runcommand ({"RepairDatabase": 1})

Serverstatus: Returns administrative statistics for this server

>db.runcommand ({"Serverstatus": 1}) Fixed collection

Fixed collections need to be created and fixed in size (number of documents, capacity). When you insert a document, if there is space, it is inserted at the end, or the oldest document is deleted. By default, fixed collections are not indexed, even "_id".

1) features

Inserting a fixed set is fast, and inserting is actually a simple memcpy (memory copy); The document itself is stored in the order in which it was inserted, and the earliest data is automatically retired when there is not enough space.

2) Create a fixed collection

Fixed collections must be created before use, using the CreateCollection () method to create:

>db.createcollection ("CollectionName", {"capped": true,size:10000,max:100})

Size: Specifies the storage space for the collection, in bytes

Max: Specifies the number of documents (optional).

When you specify a limit on the number of documents, you must specify both size. The elimination mechanism will only work based on the number of documents when the capacity is not yet full. If the capacity is full, it will work according to capacity.

3) Natural Sorting

The natural order is the order of the documents on disk. The documents for a fixed collection are always stored in the order in which they are inserted, in the same natural order, or in the order in which they are inserted in the opposite direction using natural sorting:

>db.my_collection.find (). Sort ({"$natural":-1})

4) Trailing cursor

A trailing cursor is a special persistent cursor that is not destroyed after it has no results and can only be used on a fixed set. Gridfs: Storing large files

Gridfs is a mechanism for storing binary files in MongoDB, which has the following characteristics:

Simplifies requirements without the need for a standalone file storage architecture, directly leverages established replication or fragmentation mechanisms, facilitates fault recovery and extension, avoids problems with the file system used to store user uploads, and does not produce disk fragmentation.

using Gridfs:mongofiles

With the Mongofiles application, you can use it to upload, download, list, view, or delete files in Gridfs. Use Mongofiles--help to see all options.

The basic usage is: mongofiles [options] command [GRIDFS filename]

The command has the following options: List (listing), search (view), put (upload), get (download), delete (delete)

>mongofiles put E:\MongoDB\dbData\UploadTest.txt

>mongofiles List

>mongofiles Get E:\MongoDB\dbData\UploadTest.txt

Options are the following choices:

-h[--host]: Specify the host address to upload, default localhost

--port: Specify the port number of the upload, default 27017

-u[--username]: Specify User name

-p[--password]: Specify the corresponding password

--dbpath: Specify the data file storage path

-D[--DB]: Specify the database to use

-c[--collection]: Specifies the collection to use

-l[--local]: Local file name when uploading/downloading, the default is the same as the filename on Gridfs

Internal Principle

Gridfs is a lightweight file storage specification based on ordinary MongoDB documents. The idea is to divide large files into chunks, each of which is stored as a separate document, in addition to the blocks that store the file itself, and a separate document that stores the chunked information and the metadata of the file.

By default, the block uses the Fs.chunks collection of the corresponding database, which is not indicated when it is the test database. The metadata for the file is placed under the Fs.files (default) collection.

Server-side scripting

JavaScript scripts can be executed by Db.eval () on the server side, or JavaScript scripts can be saved in the database and then invoked in other database commands.

1) db.eval ()

The function can execute arbitrary javascript code on the server, first taking the given JavaScript string to MongoDB, and then returning the result.

>db.eval ("return 1;")

The parameter can be specified by the second parameter of Eval, and is written in the form of an array.

>db.eval ("function (u) {print (' Hello, ' +u);}", ["WANGDH"])

2) storing JavaScript

Each database has a special collection called System.js, which is used to store JavaScript variables that can be invoked in any MongoDB JavaScript context.

>db.system.js.insert ({"_id": "username", "value": "WANGDH"})

System.js can also be used to store JavaScript code

>db.system.js.insert ({"_id": "Log", "Value": function (msg,level) {

var levels=["DEBUG", "WARN", "ERROR", "FATAL"];

level=level?level:0;

var now=new Date ();

Print (now+ "" +levels[level]+msg);

}})

>db.eval ("X=1;log (' x is ' +x,1)")

MongoDB Learning Notes-06 database commands, pinned sets, Gridfs, JavaScript scripts

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.