I finally ran my first Java MongoDB operation example. I don't know why MongoDB will always be locked every time I start the machine. I need to delete the lock file to start it, is it related to your own Windows 7 system? Puzzling!
- PackageMongodb;
- ImportJava.net. UnknownHostException;
- ImportCom. mongodb. BasicDBObject;
- ImportCom. mongodb. DB;
- ImportCom. mongodb. DBCollection;
- ImportCom. mongodb. DBCursor;
- ImportCom. mongodb. Mongo;
- ImportCom. mongodb. MongoException;
- /**
- * Java + MongoDB Hello world Example
- *
- */
- Public ClassMongoDb {
- Public Static VoidMain (String [] args ){
- Try{
- // Instantiate a Mongo object and connect to port 27017
- Mongo mongo =NewMongo ("Localhost",27017);
- // Connect to the database named xiaodb. If the database does not exist, mongodb will automatically create
- DB db = mongo. getDB ("Xiaodb");
- // Get collection from MongoDB, database named "xiao"
- // Obtain the data set named users from Mongodb. If the data set does not exist, Mongodb creates a new
- DBCollection collection = db. getCollection ("Users");
- // Use the BasicDBObject object to create a document for mongodb and assign a value to it.
- BasicDBObject document =NewBasicDBObject ();
- Document. put ("Id",1001);
- Document. put ("Msg","Hello world mongoDB in Java");
- // Save the newly created document to the collection.
- Collection. insert (document );
- // Create the document to query
- BasicDBObject searchQuery =NewBasicDBObject ();
- SearchQuery. put ("Id",1002);
- // Use the find method of collection to find the document
- DBCursor cursor = collection. find (searchQuery );
- // Cyclically output results
- While(Cursor. hasNext ()){
- System. out. println (cursor. next ());
- }
- System. out. println ("Done");
- }Catch(UnknownHostException e ){
- E. printStackTrace ();
- }Catch(Except exception e ){
- E. printStackTrace ();
- }
- }
- }