5) 使用>,<等比较符号
在mongodb中,也可以使用比如>,<等数量比较符号,比如要输出number>5的document集合,则使用“$gt”即可,同理,小于关系则使用$lt,例子如下:
BasicDBObject query =new BasicDBObject();
query.put("number", new BasicDBObject("$gt", 5));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
query.put("number", new BasicDBObject("$gt", 5));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
输出如下:
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c2"} , "number" : 6}
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c3"} , "number" : 7}
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c4"} , "number" : 8}
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c5"} , "number" : 9}
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c6"} , "number" : 10}
也可以多个比较符号一起使用,比如要输出number>5和number<8的document,则如下:
BasicDBObject query =new BasicDBObject();
query.put("number", new BasicDBObject("$gt", 5).append("$lt", 8));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c3"} , "number" : 7}
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c4"} , "number" : 8}
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c5"} , "number" : 9}
{"_id" : {"$oid" : "4dc7f7b7bd0fb9a86c6c80c6"} , "number" : 10}
也可以多个比较符号一起使用,比如要输出number>5和number<8的document,则如下:
BasicDBObject query =new BasicDBObject();
query.put("number", new BasicDBObject("$gt", 5).append("$lt", 8));
DBCursor cursor = collection.find(query);
while(cursor.hasNext()){
System.out.println(cursor.next());
}
同样,如果是不等于的关系的话,可以使用$ne操作符,如下:
BasicDBObject query5 =new BasicDBObject();
query5.put("number", new BasicDBObject("$ne", 8));
DBCursor cursor6 = collection.find(query5);
while(cursor6.hasNext()){
System.out.println(cursor6.next());
}
query5.put("number", new BasicDBObject("$ne", 8));
DBCursor cursor6 = collection.find(query5);
while(cursor6.hasNext()){
System.out.println(cursor6.next());
}
以上输出number=8之外的所有document。
删除document
下面我们学习如何删除document,依然以上面的已插入的1-10的documents集合为例说明:
1) 删除第一个document
DBObject doc = collection.findOne();
collection.remove(doc);
collection.remove(doc);
2) 删除指定的document
比如删除number=2的document,如下方法:
BasicDBObject document =new BasicDBObject();
document.put("number", 2);
collection.remove(document);
document.put("number", 2);
collection.remove(document);
要注意的是,如下的方法将只会删除number=3的document。
BasicDBObject document =new BasicDBObject();
document.put("number", 2);
document.put("number", 3);
collection.remove(document);
document.put("number", 2);
document.put("number", 3);
collection.remove(document);