How do I use JavaScript and MongoDB to interact under the shell? __shell

Source: Internet
Author: User
Tags create index createindex mongodb mongo shell
Client Support for MongoDB


As a very mature NoSQL database, MONGDB support for a variety of programming languages has been very perfect, and now support the major mainstream programming languages include:

1,mongo Shell

2,python

3,java

4,c#

5,node.js

6,c++



In these languages, the simplest, most lightweight of the MONGO shell, without any other dependent environment, only need a MONGO client, you can connect the local, remote MONGO library, which is very similar to the various database interface tools, such as Navicat,sql Plus, interactive ability is very strong, want what data, soon can be directly identified, of course, want to use more flexible, must be embedded in the programming language inside. Introduction to MONGODB Package Structure 1,mongo Core Script process



MONGO->mongo Interactive Shell

Mongod-> Database Process

MONGOs-> Query Routing Controller
2, Binary Import Export tool



Mongodump-> Create Bson file export from Mongod instance
Mongorestore-> Restore the backup files exported above
Bsondump-> convert Bson file into a JSON file
Mongooplog-> Record Some normal copies of streaming log 3, Text Import Export tool



Mongoimport-> to import data from CSV,JSON,TSV
Mongoexport-> export MONGO data to file in CSV,JSON,TSV format 4, diagnostic tools



Mongostat-> is able to view a copy of the current running instance, instance, collection, coll state
Mongotop-> can view the current instance's read-write ratio and time spent
Mongosniff-> provides a near-real-time data status tracking detail
Mongoperf-> is able to view the performance of the current instance disk IO How to manipulate MONGO table data in JS mode.



If we now have a demand, read a table of a MONGO library, and then clean the relevant fields, and then input into a local file, how to use JS to complete the package logic.
The definition of JS is as follows:


// Query all data of a table instance and get a cursor
var cursor = db.collection1.table1.find ();
cursor.forEach (
function (doc) {
   var split = "\ 1"; // Separator
   var anyCpyNo = doc.anyCpyNo + ""; // Primary key
   var cpyName = doc.cpyName + ""; // Enterprise name
   var logoUrl = doc.cpyOtherResource + ""! = 'undefined'? doc.cpyOtherResource.logoUrl: ""; // The URL of the picture
   var provinceCode = doc.provinceCode + ""; // Province code
   var cityCode = doc.cityCode + ""; // City code
   var modifyTime = new Date (doc.modifyTime) .getTime (); // Update time
   var cpyNatureCode = doc.cpyNatureCode + ""; // Enterprise nature + double quotes, converted into a string
   var cplen = cpyNatureCode.length
  if (cpyNatureCode! = 'undefined' && cplen> 2) {
    cpyNatureCode = cpyNatureCode + "#" + cpyNatureCode.substr (0,2) + "00";
   }
   var foundDate = new Date (doc.foundDate) .getTime (); // Found time
   var subIndustryCode = doc.subIndustryCode; // Industry standard
   if (subIndustryCode! = 'undefined' && subIndustryCode + "". length> 2) {
       subIndustryCode = subIndustryCode.substr (0,2) + "00";
   }
   var legalPerson = doc.legalPerson; // Legal representative
  if (legalPerson === 'undefined') {
      legalPerson = doc.manager;
   }
   var loc = doc.location + "" // Address
   if (loc === 'undefined') {
      loc = doc.businessPlace;
   }
   var regCode = doc.regCode + ""; // Business registration number
   var orgCode = doc.orgCode + ""; // Organization code
   var regCapital = doc.regCapital + ""! = 'undefined'? doc.regCapital.amount + ""! = 'undefined'? doc.regCapital.amount: "": ""; // Register funds
   var taxRegCode = doc.taxRegCode + ""; // Tax registration number

 var r = anyCpyNo // Primary key
  + split + cpyName // Company name
  + split + logoUrl // Image url
  + split + provinceCode // Province code
  + split + cityCode // City code
  + split + modifyTime // Update time
  + split + cpyNatureCode // Corporate Nature
  + split + foundDate // Time of establishment
  + split + subIndustryCode // The top category of the secondary industry standard
  + split + legalPerson // legal representative
  + split + loc // address
  + split + regCode // Business registration number
  + split + orgCode // Organization code
  + split + regCapital // Registered capital
  + split + taxRegCode; // Tax registration number
  r = r.replace (/ \ r / gi, ""); // Js regular remove newline characters
  r = r.replace (/ \ n / gi, ""); // Js regular removes newline characters
  r = r.replace (/ undefined / gi, ""); // Js regular removes undefined statements
  print (r); // Enter the entire line of stitching
}

);
How to submit execution JS to MONGOs in CentOS.
MONGO--quiet   ip:host/dbname <  test.js >> data
//--quiet performs silent mode, removing system printing information
//IP The IP address of the MONGO service
is//host Mogo Service provides access port
//dbname refers to the database name to be linked
//test.js is the JS file//Data we want to execute
Is that the content we output is written to the data file.
Some MONGO operation statements that correspond to SQL
Operation
SQ syntax
Mongodb syntax

Build table
CREATE TABLE users (id MEDIUM INT NOTNULL AUTO_INCREMENT, user_idVarchar (30), ageNumber, statuschar (1), PRIMARYKEY (id))
db.users.insert ({user_id: "abc123", age: 55, status: "A"})
The users collection may not exist, it will be created when the first one is inserted, of course it can
Create in advance, execute the statement: db.createCollection ("users")

New field
ALTER TABLE users ADD join_date DATETIME

db.users.update ({}, {$ set: {join_date: newDate ()}}, {multi: true})
Delete field
ALTER TABLE users DROP COLUMN join_date
db.users.update ({}, {$ unset: {join_date: ""}}, {multi: true})
Index
CREATE INDEX idx_user_id_asc ON users (user_id)
db.users.createIndex ({user_id: 1})
Create an index to specify the sort
CREATE INDEX idx_user_id_asc_age_desc ON users (user_id, ageDESC)
db.users.createIndex ({user_id: 1, age: -1})

Delete a table

DROP TABLE users

db.users.drop ()
Insert data
INSERTINT Ousers (user_id, age, status) VALUES ("bcd001", 45, "A")
db.users.insert ({user_id: "bcd001", age: 45, status: "A"})
Query 1
SELECT * FROM users
db.users.find ()
Query 2
SELECT id, user_id, status FROM users

db.users.find ({}, {user_id: 1, status: 1})

Query 3
SELECT user_id, status FROM users

db.users.find ({}, {user_id: 1, status: 1, _id: 0})

Query 4
SELECT * FROM users WHERE status = "A"
db.users.find ({status: "A"})
Query 5
SELECT user_id, status FROM users WHERE status = "A"

db.users.find ({status: "A"}, {user_id: 1, status: 1, _id: 0})
Query 6
SELECT * FROM users WHERE status! = "A"

db.users.find ({status: {$ ne: "A"}})
Query 7
SELECT * FROM users WHERE status = "A" AND age = 50

db.users.find ({status: "A", age: 50})

Query 8
SELECT * FROM users WHERE status = "A" OR age = 50
db.users.find ({$ or: [{status: "A"}, {age: 50}]})
Query 9
SELECT * FROM users WHERE age> 25

db.users.find ({age: {$ gt: 25}})

Query 10
SELECT * FROM users WHERE age <25

db.users.find ({age: {$ lt: 25}})
Query 11
SELECT * FROM users WHERE age> 25 AND age <= 50

db.users.find ({age: {$ gt: 25, $ lte: 50}})
Query 12
SELECT * FROM users WHERE user_id like "% bc%"
db.users.find ({user_id: / bc /})
Query 13
SELECT * FROM users WHERE user_id like "bc%"

db.users.find ({user_id: / ^ bc /})

Query 14
SELECT * FROM users WHERE status = "A" ORDER BY user_id ASC

db.users.find ({status: "A"}). sort ({user_id: 1})

Query 15
SELECT * FROM users WHERE status = "A" ORDERBY user_id DESC

db.users.find ({status: "A"}). sort ({user_id: -1})

Query 16
SELECT COUNT (*) FROM users

db.users.count () or
db.users.find (). count ()

Query 17
SELECT COUNT (user_id) FROM users

db.users.count ({user_id: {$ exists: true}})
db.users.find ({user_id: {$ exists: true}}). count ()

Query 18
SELECT COUNT (*) FROM users WHERE age> 30

db.users.count ({age: {$ gt: 30}}) or
db.users.find ({age: {$ gt: 30}}). count ()

Query 19
SELECTDISTINCT (status) FROMusers

db.users.distinct ("status")

Query 20
SELECT * FROM users LIMIT 1

db.users.findOne ()
db.users.find (). limit (1)

Query 21
SELECT * FROM users LIMIT 5, 10

db.users.find (). limit (5) .skip (10)

Query 22
EXPLAIN SELECT * FROM users WHERE status = "A"

db.users.find ({status: "A"}). explain ()

Update 1
UPDATE users SET status = "C" WHERE age> 25

db.users.update ({age: {$ gt: 25}}, {$ set: {status: "C"}}, {multi: true})

Update 2
UPDATE users SET age = age + 3 WHERE status = "A"

db.users.update ({status: "A"}, {$ inc: {age: 3}}, {multi: true})

Delete 1
DELETE FROM users WHERE status = "D"
db.users.remove ({status: "D"})

Delete 2
DELETE FROM users

db.users.remove ({}) 
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.