Mondodb common shell commands and common Java driver operations

Source: Internet
Author: User
Tags mongodb server

By default, MongoDB stores data in/Data/DBDirectory

Ubuntu is installed under/usr/lib/MongoDB by default.

Start the service

Start the MongoDB Server:

$ Sudo./MongoDB-path/bin/mongod

Start shell, which is connected to localhost by default:

$ Sudo./MongoDB-path/bin/Mongo> command syntax

Stop Service

#! /Bin/bashpid = 'ps-o pid, command ax | grep mongod | awk '! /Awk /&&! /Grep/{print $1} ''; if [" $ {pid }"! = ""]; Then kill-2 $ {pid}; FI

Shell:

Show DBS // all databases

Show collections // all sets of the current database
Show users // All Users
User <dB Name> // switch Database
DB. Help () // All Database Operational Commands
DB. testcollection. Help () // set all operational commands
DB. testcollection. Find () // all data in the testcollection set of the current database
DB. testcollection. Find ({Name: 'Larry '}) // search
DB. testcollection. insert ({Name: 'Larry '}) // insert

DB. testcollection. Remove ({Name: 'Larry '}) // Delete

Java API:

Mongo: connection object
DB: Database
Dbcollection: Set (similar to tables in relational databases), which can be used to add, delete, modify, and query objects.
Basicdbobject: Implements dbobject, a record.
Dbcursor: A cursor that is used to traverse the data obtained by the query and implement iterable and iterator

Getlasterror ()

By default, MongoDB does not wait for a response message. Use the getlasterror command to ensure that the operation has been correctly executed.

Write operations do not return results by default: This saves the client time to wait for a round-trip between the client and server during write operations.

Calling getlasterror will block the connection until the result is returned.

The Java driver uses writeconcern to configure the returned result.

Return Value

The return value of this command is a multi-Field object. Common fields are already listed below; other fields may exist here.

  • If OK-is true, the getlasterror command is successfully completed. It does not mean that there was no error last time.
  • Err-if it is not empty, an error occurs. The value is a description of the error body.
  • Code-if it is set, it indicates the error code.
  • Connectionid-connection ID.
  • Lastop-op-ID of the last operation

For updates:

  • N-if an update is completed, it indicates the number of updated documents.

W

  • Wnote-if it is set, it indicates that some unusual things happen here, involving the use of W:
  • Wtimeout-If timeout occurs, set this value to true.
  • Waited-if the timeout time is reached, how long will the Mark wait, in milliseconds
  • Wtime-the time spent waiting for the Operation to complete

Connect to database

Mongo M = new Mongo ("localhost"); // The default value is port 27017.
DB = M. getdb ("QA"); // obtain the database named qa. If it does not exist, create
Dbcollection question = dB. getcollection ("Question"); // obtain the set named students. If no collection exists, it is automatically created.

M. getdatabasenames (); // view all databases

DB. getcollectionnames (); // All sets in the current database

M. dropdatabase ("QA"); // delete a database

Insert data

Basicdbobject DBO = new basicdbobject ();

DBO. Put ("name", "Larry ");

Question. insert (DBO );

Question. Save (DBO );

Insert. If primary key _ id exists, no operation is performed.
Save if primary key _ id is updated

Query data

// Query all objects dbcursor cur = question. find (); While (cur. hasnext () {system. out. println (cur. next ();} // The first object question. findone (); // query the number of records question. find (). count (); // query part of the data block cur = question. find (). skip (0 ). limit (1); While (cur. hasnext () {system. out. println (cur. next ();} // compare query // "$ gt": greater than // "$ GTE": greater than or equal to // "$ lt ": less than // "$ LTE": less than or equal to // "$ in": Contains cond = new basicdbobject (); cond. put ("Age", new basicdbobject ("$ G T ", 19); cond. put ("Age", new basicdbobject ("$ gt", 19 ). append ("$ lt", 30); cond. put ("Age", new basicdbobject ("$ in", arr); pattern P = pattern. compile ("Ja? K "); cond. put ("name", P); cur = question. find (Cond); While (cur. hasnext () {system. out. println (cur. next ());}

Update:

// If the data does not exist, add

// Whether to modify Multiple matching entries

Writeconcern. None: no exception thrown writeconcern. Normal: only throw a network error exception, no server error exception

Writeconcern. SAFE: throws a network error or server error exception, and waits for the server to complete the write operation.

Writeconcern. Majority: throws a network error or server error exception, and waits for a master server to complete the write operation.

Writeconcern. fsync_safe: throw a network error or server error exception. write operation waits for the server to refresh the data to the disk.

Writeconcern. journal_safe: throw a network error or server error exception. write operation waits for the log file submitted to the disk by the server.

Writeconcern. replicas_safe: throw a network error or server error exception. Wait for at least two servers to complete the write operation.


Writeresult ret = question. update (New basicdbobject ("name", "Larry"), new basicdbobject ("$ set", new basicdbobject ("Age", 21, writeconcern. normal), true, true, writeconcern. safe );

Ret. getn () // number of records affected by the operation

Ret. getlasterror () // operation exception

Getlasterror () needs to obtain a connection from the connection pool again because MongoDB uses the connection pool, which slows down

Writeresult ret = dB. update ({"name": "Lily" },{ "$ set": {"Age": 20 }}, writeconcern. safe); If (Ret. getlasterror () = NULL) return true; else return false; <=> dB. requeststart (); // ensure that the same connection is used. The connection pool writeresult ret = dB will not be put back in the middle of the connection pool. update ({"name": "Lily" },{ "$ set": {"Age": 20 }}); If (Ret. getlasterror () = NULL) return true; else return false; dB. requestdone ();

Delete:

Question. Remove (Cond );

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.