技术开发 频道

Java Tutorial:Java操作MongoDB入门

  Getting A Single Document with A Query

  查询出单个文档

  We can create a query to pass to the find() method to get a subset of the documents in our collection. For example, if we wanted to find the document for which the value of the "i" field is 71, we would do the following ;

  可以通过find()方法查找部分document,例如,如果想查找i=71的document,这样做:

BasicDBObject query = new BasicDBObject();
query.put(
"i", 71);
cur
= coll.find(query);
while(cur.hasNext()) {
System.out.println(cur.next());
}

 

  and it should just print just one document

  会打印找到的单个document:

{ "_id" : "49903677516250c1008d624e" , "i" : 71 }

 

  You may commonly see examples and documentation in MongoDB which use $ Operators, such as this:

  MongoDB文档和例子中经常出现$操作符,如下:

db.things.find({j: {$ne: 3}, k: {$gt: 10} });

 

  These are represented as regular String keys in the Java driver, using embedded DBObjects:

  他表示驱动中预设的字符:

BasicDBObject query = new BasicDBObject();
query.put(
"j", new BasicDBObject("$ne", 3));
query.put(
"k", new BasicDBObject("$gt", 10));
cur
= coll.find(query);
while(cur.hasNext()) {
System.out.println(cur.next());
}

 

  Getting A Set of Documents With a Query

  查找多个文档

  We can use the query to get a set of documents from our collection. For example, if we wanted to get all documents where "i" > 50, we could write :

  例如,想找"i">50的文档,这样做:

query = new BasicDBObject();
query.put(
"i", new BasicDBObject("$gt", 50)); // e.g. find all where i > 50
cur = coll.find(query);
while(cur.hasNext()) {
System.out.println(cur.next());
}

 

  which should print the documents where i > 50. We could also get a range, say 20 < i <= 30 :

  会打印出i>50的文档。也可以查找范围如20:

query = new BasicDBObject();
query.put(
"i", new BasicDBObject("$gt", 20).append("$lte", 30)); // i.e. 20 < i <= 30
cur = coll.find(query);
while(cur.hasNext()) {
System.out.println(cur.next());
}
0
相关文章