---
title: "mongodb基本操作"
author: "fansofjava"
date: "2009-12-06T22:26:12Z"
tags: []
categories: ["数据库"]
slug: "mongodb"
draft: false
lastmod: "2009-12-09T00:22:16Z"
id: 542870
url: "https://fansofjava.iteye.com/blog/542870"
---

要换一种新的数据库注定要转变很多观念，以前认为可行的方式或思维，现在可能就行了，用mongodb做一个基本的CRUD也不是件容易的事，我甚至开始怀疑它是否真的有人们说的那么好，当然再自己还没有完全理解mongodb的前提下这种话还是少说点为好。
今天花了些时间试了一下基本的查询，其与mysql的JDBC查询确有很多不同。当然与Hibernate的面向对象查询也有些不同，思维真的要转变一下才行。
要了解mongodb的基本操作，最需要了解的对象就是DBCollection，这可能是整个JAVA驱动程序中最重要的一个类，当然这个类的方法也特别的多，最基本的查询方式如下：


```java

DB db = mongo.getDB("users");
DBCollection coll = db.getCollection("userCollection3");
DBCursor cur = coll.find();
while(cur.hasNext()) {
  System.out.println(cur.next());
}

```


这是最基本的查询，常用的查询方法有以下几个：

```java
find()
find( DBObject ref )
find( DBObject ref , DBObject keys )
```


find(DBObject ref)的基本用法：


```java

DBObject query = new BasicDBObject();
//条件查询
query.put("userTable", "Users");

DBCursor cur = coll.find(query);
while(cur.hasNext()) {
  System.out.println(cur.next());
}

```

如果一个对象有很多字段，而用户只需要使用其中的某些字段，可以选择性查询需要的字段，这样可以减少网络流量，这就是上面的第三个查询方法的用法，如果只需要使用userTable字段，可以这样：


```java
query.put("userTable", 1);
DBCursor cur = coll.find(new BasicDBObject(),query);
```


因为_id,_ns的值是必需返回的，所以总共会返回每条记录的_id,_ns,userTable三个字段的值。还需要注意的是不能直接通过_id字段来查找记录，至少目前没有做成功过，这一点我也不知道是为什么，于是在mongodb的客户端用命令试了一下，结果还是一样，用_id字段还是查不出东西来。_id值是系统自动生成的，如果想自定义_id的值，只需在保存对象之前覆盖_id的值即可。

官方给出一个数字条件查询的例子，也有些参考价值：


```java
query = new BasicDBObject();
query.put("i", new BasicDBObject("$gt", 20).append("$lte", 30));  //  20 < i <= 30
cur = coll.find(query);

while(cur.hasNext()) {
   System.out.println(cur.next());
}
```


另外还有些方法专门用来过虑或筛选记录的方法，如果要分页查询，就会用到这些方法，主要有两个方法：


```java

/**
     * Discards a given number of elements at the beginning of the cursor.
     * @param n the number of elements to skip
     * @return a cursor pointing to the new first element of the results
     * @throws RuntimeException if the cursor has started to be iterated through
     */
    public DBCursor skip( int n )

/**
     * Limits the number of elements returned.
     * @param n the number of elements to return
     * @return a cursor pointing to the first element of the limited results
     */
    public DBCursor limit( int n )

```


由于本人着实有些懒，所以不一翻译。


如果查询某一条记录，可以使用以下方法：

```java
findOne()
findOne( DBObject o )
findOne( DBObject o, DBObject fields )
```


上面方法使用的基本方式与find系列方法完全一样，只是它们只返回其中的一条记录。

讲完查询，讲一讲关于怎样修改记录。既然不能直接通过_id查询记录，那么修改的时候也会麻烦一点，修改对象的方法主要有两种，第一种是用save方法：


```java

......
DBObject q = coll.findOne(user);
q.put("userTable", "Users2");
coll.save(o);

```


第二种是用update方法修改对象：


```java
DBObject q = coll.findOne(user);

DBObject o = new BasicDBObject();
o.put("name", "fansof");
o.put("password", "java");

coll.update(q, o);
```


可以看出通过update方法修改时，可以把原来的对象替换成新的对象，哪怕新的对象的结构与原来对象的字段结构不一样也可以。所以使用update更新时，需非常谨慎才行。

额外讲点东西，深入一下update会发现，update也有几种形式：


```java
public abstract DBObject update( DBObject q , DBObject o , boolean upsert , boolean multi ) throws MongoException ;
public DBObject update( DBObject q , DBObject o ) throws MongoException {
        return update( q , o , false , false );
}
public DBObject updateMulti( DBObject q , DBObject o ) throws MongoException {
        return update( q , o , false , true );
}
```


其实源码的注释对有些参数解释得不是很清楚，不过官方网站上正好有关于update的介绍：

```java
/**
*db.collection.update( criteria, objNew, upsert, multi )
*Arguments:
*criteria - query which selects the record to update; 
*objNew - updated object or $ operators (e.g., $inc) which manipulate the object 
*upsert - if this should be an "upsert"; that is, if the record does not exist, insert it 
*multi - if all documents matching criteria should be updated (the default is to *only update the first document found) 
*/
```

上面有个参数名叫upsert，意思是："update if present; insert is missing"。

删除相对来说，来简单一些，因为方法比较单一，如：

```java

DBObject user = new BasicDBObject();
user.put("userTable", "用户表4");
		
DBObject o = coll.findOne(user);
coll.remove(o);

```



到此，mongodb的基本操作就讲完了，其它相对高级一点的用法以后有时间再试一下。