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