找网上的资料看了下增删改查,等日后补上。
已经实现了数据的插入,现在想通过 _id属性来查找数据。一开始看到 类似 55b321df715cc162076eb466 这么一长串的内容觉得是string类型。但是发现并不能搜索到结果,在网上搜到了解决方案:
String sid = "55b321df715cc162076eb466";
sitem.put("_id", new ObjectId(sid));
cursor = collection.find(sitem);
通过ObjectId类型就可以查找数据了。
demo源代码:
package persistence;
import java.net.UnknownHostException;
import java.util.Date;
import org.bson.types.ObjectId;
import net.sf.json.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import domain.Article;
public class TestMongo {
public static void main(String[] args) {
Mongo mongo = null;
try {
// 8908 mongo.duapp.com smbWruErqVUXLgjDDSEG
mongo = new Mongo("localhost", 27017);
System.out.println("connection success");
DB db = mongo.getDB("myblog");
DBCollection collection = db.getCollection("article");
BasicDBObject item = new BasicDBObject();
item.put("title", "Rectangle Area");
item.put("date", new Date());
item.put(
"extract",
"Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.");
String content = "Assume that the total area is never beyond the maximum possible value of int.这道题求得是两个举行覆盖的面积。如果两个矩形没有相交的话直接返回两个矩形面积之和就可以了,如果有重合,那么再减去重合的面积即可。在如何计算重合面积上花费了一些时间,感觉思维还是有待加强。代码:";
item.put("content", content);
collection.insert(item);
String sid = "55b321df715cc162076eb466";
Object sido = new Object();
DBCursor cursor = collection.find();
while (cursor.hasNext()) {
// System.out.println("result:"+cursor.next());
DBObject o = cursor.next();
/*
* String id =(String) o.get("_id").toString(); sido =
* o.get("_id"); System.out.println(id); sid = id; String title
* =(String) o.get("title"); System.out.println(title);
*
* Date date =(Date) o.get("date");
* System.out.println(date.getDate());
*
* String extract =(String) o.get("extract");
* System.out.println(extract);
*/
System.out.println("search for id:" + sid);
BasicDBObject sitem = new BasicDBObject();
sitem.put("_id", new ObjectId(sid));
cursor = collection.find(sitem);
while (cursor.hasNext()) {
System.out.println("found result:");
System.out.println(cursor.next().get("date").toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
结果: