package mongodb;
import java.util.ArrayList;
import java.util.List;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoCredential;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
public class MongodbSelect {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
// 認證
MongoCredential journaldevAuth = MongoCredential.createMongoCRCredential("your username", "your database", "your password".toCharArray());
List auths = new ArrayList();
auths.add(journaldevAuth);
//連線
ServerAddress serverAddress = new ServerAddress("your server", your port);
MongoClient mongo = new MongoClient(serverAddress,auths);
//選擇連線database
DB db = mongo.getDB("your database");
//選擇collection (table)
DBCollection site = db.getCollection("site");
//iterate the table
System.out.println();
System.out.println("iterate the table");
DBCursor cursor = site.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//query --> city==Taipei
System.out.println();
System.out.println("query --> city==Taipei");
BasicDBObject query = new BasicDBObject("city", "taipei");
cursor = site.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//query --> num>=50 && city==Taipei
System.out.println();
System.out.println("query --> num>=50 && city==Taipei");
query = new BasicDBObject("num", new BasicDBObject("$gte", 50))
.append("city", "taipei");
cursor = site.find(query);
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//query num > 20 && num<=30
//only display columns city , address
System.out.println();
System.out.println("query num > 20 && num<=30");
System.out.println("only display columns city , address");
query = new BasicDBObject("num", new BasicDBObject("$gt", 20).append("$lte", 30));
cursor = site.find(query, new BasicDBObject("city",true).append("address", true));
try {
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
//iterate the table and sort by num
System.out.println();
System.out.println("iterate the table and sort by num");
cursor = site.find().sort(new BasicDBObject("num",1));
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
}
catch(UnknownHostException ex)
{
}
}
}
2015-09-16
MongoDB using Java Part 3 - select
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment