Basic use of MongoDB and Java to the basic additions and deletions of MongoDB

Source: Internet
Author: User
Tags create mongodb dname mongoclient object object

Features of MongoDB

    • MongoDB is a document storage database with flexible storage structure
    • MongoDB supports complex query operations, support sequences
    • MongoDB uses C + + development, can do distributed extension
    • MongoDB is stored in bson format
    • MongoDB supports JS engine, can write JS statement block
Installation and use

1. Run as administrator cmd.exe into the command line console and start the Mongod server,

mongod --dbpath F:\mongodb\data --logpath F:\mongodb\logs\a.log
启动mongo客户端:mongo


2. Start the server as a window service

Run Cmd.exe as administrator into the command line console

    • Execute the Create MongoDB service command

      mongod --dbpath F:\mongodb\data --logpath F:\mongodb\logs\a.log --serviceName MongoDB --install
    • Start and stop MongoDB services

      net start MongoDBnet stop MongoDB
    • Delete MongoDB Service (stop service first)

      sc delete MongoDB

MongoDB Operations Command Library Operations (user space)
    • Show DBS//See which libraries are available
    • Use XXX//create using a library
    • Db.dropdatabase ()//delete current Library
Collection Operations (table)
    • Show collections//See which collections are in the current library
    • Db.xxx.insert ()//Automatically create a collection when inserting records
    • Db.xxx.drop ()//delete collection
Record Action (record)
    • Db.xxx.insert ()//Insert Record

      db.emp.insert({"empno":1001,"ename":"tom"})db.dept.insert([{"dno":111,"dname":"ui"},{"dno":112,"dname":"h5"}])for(var i=1;i<100;i++){    db.dept.insert({"dno":i,"dname":"java"+i});};
    • Db.xxx.find ()//enquiry Record

      db.emp.find()db.dept.find({"dno":50})db.dept.find({"dno":{$gt:90}})db.dept.find({"dname":/h/})
    • Db.xxx.update ()//update record

      //整体更新db.dept.update({"dno":2},{"dname":"php"})//局部更新db.dept.update({"dno":3},{$set:{"dname":"h5"}})//更新多条记录,第三个false表示没有符合记录不插入;true表示插入。第四个参数true表示多行更新;false表示单行db.dept.update({"dno":{$lt:10}},{$set:{"dname":"JAVA"}},false,true)
    • Db.xxx.remove ()//delete record

      db.emp.remove({})db.dept.remove({"dno":1})db.dept.remove({"dno":{$gt:50}})
Other operations
    • Statistics

      //统计dept记录数量db.dept.count()//获取dname值,去重db.dept.distinct("dname")
    • Sort

      //按dname降序排列db.dept.find().sort({"dname":-1})//按dname升序排列db.dept.find().sort({"dname":1})
    • Page out

      //获取前5条记录db.dept.find().limit(5)//跳过5条再取5条(取6-10)db.dept.find().skip(5).limit(5)
    • Index

      db.dept.ensureIndex({"dname":1})        db.dept.dropIndexes()db.dept.find({"dname":"java99999"}).explain("executionStats")

Java access MongoDB based on Mongo-java package basic access

API Introduction

- MongoClient  连接对象  Mongo- MongoDatabase 库对象   DB- MongoCollection 集合对象  DBCollection- MongoCursor 查询结果集对象 DBCoursor- Document 记录对象  DBObject

 Public classmongodbtest {@Test Public voidtest1 () {mongoclient m=NewMongoclient ("localhost", 27017); Mongoiterable<String> dbs = M.listdatabasenames ();//Querying the Database listMongocursor<string> iterator =Dbs.iterator ();  while(Iterator.hasnext ()) {System.out.println (Iterator.next ()); }    }    //Query All tests@Test Public voidtest2 () {mongoclient m=NewMongoclient ("localhost", 27017); Mongodatabase DBS= M.getdatabase ("java20");//Querying database Names        ///Query database table/JAVA20.JAVA20Mongocollection<document> collection = Dbs.getcollection ("Java20"); Mongocursor<Document> cusor = Collection.find (). iterator ();//Querying Data//Iterate with iterators         while(Cusor.hasnext ()) {Document Next=Cusor.next (); Object Object= Next.get ("User"); String name= next.getstring ("name"); String pwd= Next.getstring ("pwd"); System.out.println ("UserID" + Object + "Name:" + name + "| |:P assword:" +pwd); }    }        //Filter Query Test@Test Public voidtest3 () {mongoclient m=NewMongoclient ("localhost", 27017); Mongodatabase Database= M.getdatabase ("Java20"); Mongocollection<Document> collections = Database.getcollection ("Java20"); //Bson filter = filters.lt ("DNO", ten);//{"DNO": {$lt: ten}}Bson lt = filters.lt ("User", 10); Mongocursor<Document> documents =Collections.find (LT). iterator ();  while(Documents.hasnext ()) {Document D=Documents.next (); Object userid= D.get ("User"); Object name= D.get ("name"); Object pwd= D.get ("pwd"); System.out.println ("ID:" + userid + "name is:" + name + "Password is:" +pwd);    } m.close (); }    //Insert Test@Test Public voidtest4 () {mongoclient m=Newmongoclient (); Mongodatabase Database= M.getdatabase ("java20");//use a database of java20mongocollection<document> coll= database.getcollection ("emp");//Find the EMP table and create a table without an EMP tableDocument Doc=NewDocument (); Doc.put ("Eno", 1003); Doc.put ("Ename", "being"); Doc.put ("Salary", 5755);    Coll.insertone (DOC); }        //Local Updates@Test Public voidTest5 () {mongoclient m=NewMongoclient ("localhost", 27017); Mongodatabase Database= M.getdatabase ("java20");//Gets the library name of the current databasemongocollection<document> emp = database.getcollection ("emp");//Bson where= Filters.eq ("Eno", 1002);//Document Doc=NewDocument (); Doc.put ("Salary", 8356);//{"Salary": 4646}Document up=NewDocument (); Up.put ("$set", Doc);//{$set: {"Salary": 5657}}//updates are used hereEmp.updateone (where, up);    M.close (); }        //All Updates@Test Public voidTest6 () {mongoclient m=NewMongoclient ("localhost", 27017); Mongodatabase Database= M.getdatabase ("Java20"); Mongocollection<Document> emp = database.getcollection ("emp")); Bson eq= Filters.eq ("Eno", 1003); //System.out.println (eq); Filter{fieldname= ' Eno ', value=1003}Document doc=NewDocument (); Doc.put ("Salary", 500); //the replacement is used hereEmp.replaceone (EQ, doc);//All UpdatesM.close (); }}

Basic use of MongoDB and Java to the basic additions and deletions of MongoDB

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.