3) 使用in 操作符号指定删除document
下面的例子将同时删除number=4和number=5的document,使用的是in操作符
BasicDBObject query2 =new BasicDBObject();
List list =new ArrayList();
list.add(4);
list.add(5);
query2.put("number", new BasicDBObject("$in", list));
collection.remove(query2);
List list =new ArrayList();
list.add(4);
list.add(5);
query2.put("number", new BasicDBObject("$in", list));
collection.remove(query2);
4) 使用“$gt”删除大于某个值的document
BasicDBObject query =new BasicDBObject();
query.put("number", new BasicDBObject("$gt", 9));
collection.remove(query);
query.put("number", new BasicDBObject("$gt", 9));
collection.remove(query);
以上会删除number=10的document。
5) 删除所有的document
DBCursor cursor = collection.find();
while(cursor.hasNext()){
collection.remove(cursor.next());
}
while(cursor.hasNext()){
collection.remove(cursor.next());
}
保存图片到Mongodb
下面将讲解如何使用Java MongoDB GridFS API去保存图片等二进制文件到Monodb,关于Java MongoDB GridFS API的详细论述,请参考http://www.mongodb.org/display/DOCS/GridFS+Specification
1)保存图片
代码段如下:
String newFileName ="mkyong-java-image";
File imageFile =newFile("c:\\JavaWebHosting.png");
GridFS gfsPhoto =new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
File imageFile =newFile("c:\\JavaWebHosting.png");
GridFS gfsPhoto =new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
这里,将c盘下的JavaWebHosting.png保存到mongodb中去,并命名为mkyong-java-image。
2) 读取图片信息
代码段如下
String newFileName ="mkyong-java-image";
GridFS gfsPhoto =new GridFS(db, "photo");
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
System.out.println(imageForOutput);
GridFS gfsPhoto =new GridFS(db, "photo");
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
System.out.println(imageForOutput);
将会输出JSON格式的结果;
{
"_id" :
{
"$oid" : "4dc9511a14a7d017fee35746"
} ,
"chunkSize" : 262144 ,
"length" : 22672 ,
"md5" : "1462a6cfa27669af1d8d21c2d7dd1f8b" ,
"filename" : "mkyong-java-image" ,
"contentType" : null ,
"uploadDate" :
{
"$date" : "2011-05-10T14:52:10Z"
} ,
"aliases" : null
}
"_id" :
{
"$oid" : "4dc9511a14a7d017fee35746"
} ,
"chunkSize" : 262144 ,
"length" : 22672 ,
"md5" : "1462a6cfa27669af1d8d21c2d7dd1f8b" ,
"filename" : "mkyong-java-image" ,
"contentType" : null ,
"uploadDate" :
{
"$date" : "2011-05-10T14:52:10Z"
} ,
"aliases" : null
}
可以看到,输出的是文件的属性相关信息。