技术开发 频道

Java Tutorial:Java操作MongoDB入门

  Inserting a Document

  插入一个文档(类似一条记录)

  Once you have the collection object, you can insert documents into the collection. For example, lets make a little document that in JSON would be represented as

  得到collection对象就可以把documents插入到collection中。例如,创建一个如下的JSON文档:

{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"info" : {
x :
203,
y :
102
}
}

  Notice that the above has an "inner" document embedded within it. To do this, we can use the BasicDBObject class to create the document (including the inner document), and then just simply insert it into the collection using the insert() method.

  注意,上面的文档中有个内部文档(就是{ x : 203, y : 102})。存储上面的文档,可以使用BasicDBObject 类来创建文档(包括inner文档),使用insert()方法可以简单的把文档插入collection中。

BasicDBObject doc = new BasicDBObject();
doc.put(
"name", "MongoDB");
doc.put(
"type", "database");
doc.put(
"count", 1);
BasicDBObject info
= new BasicDBObject();
info.put(
"x", 203);
info.put(
"y", 102);
doc.put(
"info", info);
coll.insert(doc);

  Finding the First Document In A Collection using findOne()

  使用findOne()方法查找collection中的第一个文档document

  To show that the document we inserted in the previous step is there, we can do a simple findOne() operation to get the first document in the collection. This method returns a single document (rather than the DBCursor that the find() operation returns), and it's useful for things where there only is one document, or you are only interested in the first. You don't have to deal with the cursor.

  可以使用findOne()操作来查找collection中的第一个文档来显示上一步中插入的文档。方法返回一个文档,用来找只有一个文档或第一条文档很实用。可以不使用cursor(游标):

DBObject myDoc = coll.findOne();
System.out.println(myDoc);

  and you should see

  打印的结果:

{ "_id" : "49902cde5162504500b45c2c" , "name" : "MongoDB" , "type" : "database" , "count" : 1 , "info" : { "x" : 203 , "y" : 102}}

  Note the _id element has been added automatically by MongoDB to your document. Remember, MongoDB reserves element names that start with "_"/"$" for internal use.

  注意,_id元素是MongoDB自动添加的。MongoDB内部的元素以"_"/"$"开始。

0
相关文章