Using Java to manipulate MongoDB

Source: Internet
Author: User
Tags mongodb support

1. Environmental preparedness

Download MongoDB support for Java driver package

Drive Pack: Https://github.com/mongodb/mongo-java-driver/downloads

2. Querying all documents in the collection

Mongo Mongo = new Mongo ("localhost", 27017);D b DB = mongo.getdb ("test");D bcollection collection = Db.getcollection (" Customer ");D bcursor dbcursor = Collection.find (); System.out.println (Collection.getcount ()); while (Dbcursor.hasnext ()) {System.out.println (Dbcursor.next ());} Mongo.close ();

3. Delete a document from the collection

Mongo Mongo = new Mongo ("localhost", 27017);D b DB = mongo.getdb ("test");D bcollection collection = Db.getcollection (" Customer "); Basicdbobject o = new Basicdbobject ("_id", New ObjectId ("5199ee647d5fc789bc760c07")); Collection.remove (o); Mongo.close ();

4. Inserting a document into the collection

Mongo Mongo = new Mongo ("localhost", 27017);D b DB = mongo.getdb ("test");D bcollection collection = Db.getcollection (" Customer ");D bobject C = new Basicdbobject (), C.put (" name "," Jack "), C.put (" Age "), Collection.insert (c); Mongo.close ( );

5. Updating documents in the collection

Mongo Mongo = new Mongo ("localhost", 27017);D b DB = mongo.getdb ("test");D bcollection collection = Db.getcollection (" Customer "); Basicdbobject query = new Basicdbobject ("_id", New ObjectId ("519e2e393296cf3baccdb10c")); Basicdbobject object = (basicdbobject) collection.findone (query); Object.put ("Name", "Wangwu"); int n = Collection.update (Query, Object). GETN (); SYSTEM.OUT.PRINTLN (n); Mongo.close ();

  

  

 

Using Java to manipulate 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.