Java operation MongoDB
First introduce the mongo-java-dirver driver
Org.mongodb mongo-java-driver 3.4.2
Code operation demonstration:
Package com.simple.database.test;import java.util.ArrayList;import java.util.List;import org.bson.Document;import org.bson.conversions.Bson;import com.mongodb.MongoClient;import com.mongodb.client.FindIterable;import com.mongodb.client.MongoCollection;import com.mongodb.client.MongoCursor;import com.mongodb.client.MongoDatabase;import com.mongodb.client.model.Filters / * java operation MongoDB * @ author root * / public class HelloMongoDB {public static void main (String [] args) {try {/ / 1, connect to MongoDB service MongoClient mc = new MongoClient ("127.0.0.1", 27017) / / 2. Connect to the specified database MongoDatabase db = mc.getDatabase ("demodb"); / / 3. Create a collection / / db.createCollection ("simplelife") / / 4. Get the collection MongoCollection collection = db.getCollection ("users"); / / 5. Insert document data / / insertCollectionData (collection) / 6. Query the document data findCollectionData (collection); / 7, update the document data / / modify the likes=100 document in the document to likes=200 updateCollectionData (collection) / / 8. Delete the first document data collection.deleteMany (Filters.eq ("likes", 200); collection.deleteOne (Filters.eq ("likes", 100);} catch (Exception e) {e.printStackTrace () System.out.println (e.getClass (). GetName () + "." + e.getMessage ();}} private static void updateCollectionData (MongoCollection collection) {Bson filter = Filters.eq ("likes", 100); Document update = new Document ("$set", new Document ("likes", 200); collection.updateMany (filter, update) } private static void findCollectionData (MongoCollection collection) {FindIterable findIterable = collection.find (); MongoCursor mongoCursor = findIterable.iterator (); while (mongoCursor.hasNext ()) {System.out.println (mongoCursor.next ()) }} / * insert document 1, create document org.bson.Document parameter key-value format * 2, create document collection List * 3, Insert a document collection into a database collection: mongoCollection.insertMany (List) * insert a single document using: mongoCollection.insertOne (Document) * / private static void insertCollectionData (MongoCollection collection) {Document document = new Document ("title") "MongoDB") Document.append ("description", "database"). Append ("likes", 100) .append ("by", "Fly"); List documents = new ArrayList (); documents.add (document); collection.insertMany (documents); System.out.println ("document inserted successfully!") ;}}