1024programmer Mongodb Java operation MongoDB quick start tutorial

Java operation MongoDB quick start tutorial

https://github.com/mongodb/mongo-java-driver/downloads

Just download the jar package of hundreds of K. I downloaded mongo-2.9.0-RC2.jar 389K

After downloading, put it into the java project and import it
Take the previous test

Start mongo.
Then write a java program

package com.javaer.mongo;
import java.net.UnknownHostException;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
public class SimpleConnection {
/**
* @param args
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException {
Mongo m = new Mongo();
/**
* Other connection methods
* Mongo m = new Mongo(“localhost”);
* Mongo m = new Mongo(“localhost”,27017);
* Mongo m = new Mongo(Arrays.asList(new ServerAddress(“localhost”, 27017),
New ServerAddress(“localhost”, 27018),
New ServerAddress(“localhost”, 27019)));
*/
DB db = m.getDB(“yuexiaosheng”);
//List all connections
      Set colls = db.getCollectionNames();
for (String s : colls) {
System.out.println(“connection:” + s);
}
//Read a piece of data
DBCollection coll = db.getCollection(“mycollection”);
DBObject myDoc = coll.findOne();
System.out.println(myDoc);
/**
//Insert a piece of data
BasicDBObject doc = new BasicDBObject();
Doc.put(“title”,”tom is 2.8″);
Doc.put(“online”,”true”);
       coll.insert(doc);
*/
//Read the total number of collection records
System.out.println(coll.getCount());
//Traverse collection records
DBCursor cursor = coll.find();
try {
  while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
Cursor.close();
}
System.out.println(“——————————————- —————————-“);
//Search for a record
BasicDBObject query = new BasicDBObject();
query.put(“title”, “tom is 2.8”);
Cursor = coll.find(query);
try {
  while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
Cursor.close();
}
}
}

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/java-operation-mongodb-quick-start-tutorial/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索