使用:mongo-java-driver-3.5.0
其实搜索mongo 当中_id(ObjectId)的值特别简单,只是不知道某度搜索的是什么东西,强推Google
附代码:
public static void find(String collectionName) {
System.out.println("----查询指定条件的文档----");
MongoCollection<Document> collection = mgdb.getCollection(collectionName);
FindIterable<Document> findIterable = collection.find().projection(Projections.include("_id")); //获取表中所有内容
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext())
{ Document out1=mongoCursor.next(); //创建一个新的Document,并将mongoCursor中的document赋上
ObjectId a=out1.getObjectId("_id"); //获取文档当中的ObjectId
System.out.println(a);
//String a=ObjectId.toString 保存在String当中
}
其实也就一行
mongoCursor..next().getObjectId("_id").toString()
使用by id的更新:
mgdb.getCollection(table).updateOne(new BasicDBObject("_id", new ObjectId(_id)), //_id可以是String类型的变量
new BasicDBObject("$set", new BasicDBObject(type,value)));
表示update更新 table当中id是_id的document 的type属性更改为value(有点长)
以上