技术开发 频道

Java Tutorial:Java操作MongoDB入门

  Adding Multiple Documents

  添加多个文档

  In order to do more interesting things with queries, let's add multiple simple documents to the collection. These documents will just be

  为了方便下面的讲解,我们来添加多个简单的文档,如下:

{
"i" : value
}

  and we can do this fairly efficiently in a loop

  用循环来快速的实现:

for (int i=0; i < 100; i++) {
coll.insert(
new BasicDBObject().append("i", i));
}

  that we can insert documents of different "shapes" into the same collection. This aspect is what we mean when we say that MongoDB is "schema-free"

  注意,可以在一个collection中插入不同类型的文档。就是说MongoDB是"schema-free"(什么意思?)

  Counting Documents in A Collection

  统计collection中所有的document数量

  Now that we've inserted 101 documents (the 100 we did in the loop, plus the first one), we can check to see if we have them all using the getCount() method.

  现在,插入了101个文档(循环的100个和第一个),使用getCount()检查一下。

System.out.println(coll.getCount());

  and it should print 101.

  输出结果是101.

  Using a Cursor to Get All the Documents

  使用游标查找所有的文档

  In order to get all the documents in the collection, we will use the find() method. The find() method returns a DBCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out :

  使用find()来查找所有的document。find()方法查询返回一个可以遍历文档集合的DBCursor 对象。如下:

DBCursor cur = coll.find();
while(cur.hasNext()) {
System.out.println(cur.next());
}

  and that should print all 101 documents in the collection.

  打印所有的document

0
相关文章