How do I use JavaScript and MongoDB interaction under the shell?

Source: Internet
Author: User
Tags createindex mongo shell

Client Support for MongoDB

As a very mature NoSQL database, MONGDB support for a variety of programming languages has been perfected, and currently supports major mainstream programming languages including:

1,mongo Shell

2,python

3,java

4,c#

5,node.js

6,c++

In these languages, the simplest, the lightest is 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 and so on, interactive ability is very strong, want what data, quickly can detect directly, of course want to use more flexible, certainly is embedded in the programming language inside.

MONGODB Package Structure Introduction 1,mongo core script process

MONGO->mongo's interactive shell

Database Process Mongod

MONGOs, Query routing controller

2, Binary Import Export tool

Mongodump Create Bson file export from Mongod instance
Mongorestore. Restore the exported backup file above
Convert Bson files to JSON file Bsondump
Mongooplog, logging Some normal copies of streaming log

3, Text Import and Export tool

Import data from CSV,JSON,TSV, Mongoimport
Mongoexport export MONGO data to CSV,JSON,TSV formatted file

4, diagnostic tools

Mongostat to view copies, instances, collections, coll states of the current running instance
Mongotop to view the read and write ratio and time spent on the current instance
Mongosniff provides a near real-time data status tracking detail
Mongoperf to view the performance of the current instance disk IO

How to manipulate MONGO table data in JS mode?

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

//Query a table instance for all data, get a cursorvarCursor=db.collection1.table1.find (); Cursor.foreach ( function(doc) {    varsplit="\1";//Delimiter   varanycpyno=doc.anycpyno+"";//PRIMARY key   varcpyname=doc.cpyname+"";//Enterprise name   varLogourl=doc.cpyotherresource+""!=' undefined '? DOC.CPYOTHERRESOURCE.LOGOURL:"";//URL of picture   varProvincecode=doc.provincecode+"";//Province code   varCitycode=doc.citycode+"";//City Code   varModifytime=New Date(Doc.modifytime). GetTime ();//Update Time   varCpynaturecode=doc.cpynaturecode+"";//Enterprise Nature + double quotes, turn into string   varCplen=cpynaturecode.lengthif(cpynaturecode!=' undefined '&& Cplen >2) {cpynaturecode=cpynaturecode+"#"+CPYNATURECODE.SUBSTR (0,2)+"XX"; }varFounddate=New Date(doc.founddate). GetTime ();//Set-up time   varSubindustrycode=doc.subindustrycode;//Industry standard   if(subindustrycode!=' undefined '&& subindustrycode+"". length >2) {Subindustrycode=subindustrycode.substr (0,2)+"XX"; }varLegalperson=doc.legalperson;//legal representative  if(legalperson===' undefined ') {Legalperson=doc.manager; }varloc=doc.location+""//Address   if(loc===' undefined ') {loc=doc.businessplace; }varRegcode=doc.regcode+"";//Industrial registration number   varOrgcode=doc.orgcode+"";//Organization Code   varregcapital=doc.regcapital+""!=' undefined '? doc.regcapital.amount+""!=' undefined '? Doc.regCapital.amount:"":"";//Registered capital   varTaxregcode=doc.taxregcode+"";//Tax Registration number varR=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//Enterprise Nature+split+founddate//Set-up time+split+subindustrycode//Level two industry standard category+split+legalperson//legal representative+split+loc//Address+split+regcode//Industrial registration number+split+orgcode//Organization Code+split+regcapital//Registered capital+split+taxregcode;//Tax Registration numberR=r.replace (/\r/gi,"");//js to remove newline charactersR=r.replace (/\n/gi,"");//js to remove newline charactersR=r.replace (/undefined/gi,"");//js to remove undefined statementsPrint (R);//Input the entire line of stitching} );
How do I submit a JS to MONGOs in CentOS?
--quiet   ip:host/dbname <  test.js >> data//--quiet执行静默模式,去掉系统打印信息//ip mongo服务所在机的ip地址//host mogo服务对外提供的访问端口//dbname 是指要链接的数据库名字// test.js 是我们要执行的js文件// data 是我们输出的内容写入data文件里面
Some MONGO SQL-related action statements
Operation SQ syntax mongodb syntax build tableCREATE TABLEUsers (ID MEDIUMINTNotnull Auto_increment,user_idvarchar ( -), Agenumber,statuschar (1), PRIMARYKEY (ID)) db.users.Insert({user_id:"abc123", Age: -, Status:"A"}) The users collection may not exist, it will be created when the first article is inserted, or it can be created ahead of time, executing the statement: Db.createcollection ("Users") New fieldsALTER TABLEUsersADDJoin_date datetimedb.users.Update({},{$Set: {join_date:newdate ()}},{multi:true}) Delete FieldALTER TABLEUsersDROP COLUMNJoin_datedb.users.Update({},{$unset: {join_date:""}},{multi:true}) Build the indexCREATEINDEX IDX_USER_ID_ASC onUsers (user_id) Db.users.createIndex ({user_id:1}) Set the index to specify the sortCREATEINDEX Idx_user_id_asc_age_desc onUsers (User_id,agedesc) Db.users.createIndex ({user_id:1, age:-1}) Delete a tableDROP TABLEUsersdb.users.Drop() inserting Data insertint ousers (user_id,age,status)VALUES("bcd001", $,"A") Db.users.Insert({user_id:"bcd001", Age: $, Status:"A"}) query1SELECT* fromUsersdb.users.find () query2 SELECTId,user_id,status fromUsersdb.users.find ({},{user_id:1, Status:1}) query3SELECTUser_id,status fromUsersdb.users.find ({},{user_id:1, Status:1, _id:0}) query4SELECT* fromUsersWHEREStatus ="A"Db.users.find ({status:"A"}) query5 SELECTUser_id,status fromUsersWHEREStatus ="A"Db.users.find ({status:"A"},{USER_ID:1, Status:1, _id:0}) query6SELECT* fromUsersWHEREStatus! ="A"Db.users.find ({status:{$ne:"A"}}) query7SELECT* fromUsersWHEREstatus="A"  andAge= -Db.users.find ({status:"A", Age: -}) query8SELECT* fromUsersWHEREstatus="A" ORAge = -Db.users.find ({$or: [{Status:"A"},{age: -}]}) query9SELECT* fromUsersWHEREAge > -Db.users.find ({age:{$gt: -}}) queryTenSELECT* fromUsersWHEREAge < -Db.users.find ({age:{$lt: -}}) query OneSELECT* fromUsersWHEREAge > -  andAge <= -Db.users.find ({age:{$gt: -, $lte: -}}) query ASELECT* fromUsersWHEREuser_id like "%bc%"Db.users.find ({user_id:/bc/}) query -SELECT* fromUsersWHEREuser_id like "bc%"Db.users.find ({user_id:/^bc/}) query -SELECT* fromUsersWHEREstatus="A" ORDER  byuser_idASCDb.users.find ({status:"A"}). Sort ({user_id:1}) query theSELECT* fromUsersWHEREstatus="A"user_idDESCDb.users.find ({status:"A"}). sort ({user_id:-1}) query -SELECT COUNT(*) fromUsersdb.users.Count() or Db.users.find ().Count() query -SELECT COUNT(user_id) fromUsersdb.users.Count({user_id:{$exists:true}}) Db.users.find ({user_id:{$exists:true}}).Count() query -SELECT COUNT(*) fromUsersWHEREAge> -Db.users.Count({age:{$GT: -}}) or Db.users.find ({age:{$gt: -}}).Count() query +SelectDistinct (status) fromusersdb.users.distinct("Status") query -SELECT* fromUsers LIMIT1Db.users.findOne () Db.users.find (). Limit (1) query +SELECT* fromUsers LIMIT5,TenDb.users.find (). Limit (5). Skip (Ten) query AEXPLAINSELECT* fromUsersWHEREstatus="A"Db.users.find ({status:"A"}). Explain () update1UPDATEUsersSETstatus="C" WHEREAge> -Db.users.Update({age:{$GT: -}},{$Set: {Status:"C"}},{multi:true}) Update2 UPDATEUsersSETAge=age+3 WHEREstatus="A"Db.users.Update({status:"A"},{$inc: {age:3}},{multi:true}) Delete1DELETE  fromUsersWHEREstatus="D"Db.users.remove ({status:"D"}) Delete2DELETE  fromUsersdb.users.remove ({})

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How do I use JavaScript and MongoDB interaction under the shell?

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.