日期:2014-05-16  浏览次数:20529 次

java操作mongodb(二)之修改、删除及其他

接上文,主要整理了java操作mongodb的一些基本概念以及新增、查询等操作,本文对修改、删除等做一些总结

1、修改、删除

删除操作

//根据指定条件删除,与下面方法一致,调用默认WriteConcern.NORMAL:网络错误时抛出异常
collection.remove(new BasicDBObject("name", "robin"));
//根据指定条件删除,指定写入模式
collection.remove(new BasicDBObject("username", "robin"), WriteConcern.NORMAL);

更新提供了一个多态的方法供使用:

/**
*q         根据条件查询需要更新的记录
*o         更新集合
*upsert 如果没有记录q是否插入
*multi    是否更新多条
*/
public abstract WriteResult update( DBObject q , DBObject o , boolean upsert , boolean multi , WriteConcern concern, DBEncoder encoder );

?如:

//根据age=32更新,注意更新后该文档只有username=jack,同时多条只会更新一条,不存在不会插入
WriteResult cursor = collection.update(new BasicDBObject("age", 32), new BasicDBObject("username", "jack"));
//根据age来更新,会追加熟悉gengder=male
collection.update(new BasicDBObject("age", 33), new BasicDBObject("$set", new BasicDBObject("gender", "male")));

//根据username来更新,修改age如果没有追加,更新所有满足条件的文档
collection.update(new BasicDBObject("username", "jack"),
        new BasicDBObject("$set", new BasicDBObject("age", 32)), false, true);

//根据username更新,且age+10
collection.updateMulti(new BasicDBObject("username", "jack"), new BasicDBObject("$inc", new BasicDBObject(
        "age", 10)));

以上各个方法都返回WriteResult,需要返回更多信息可以通过WriteConcern来设置。同时还提供了其他接口来获取更新的数据(包括更新前或更新后的数据)

 /**
     * Finds the first document in the query and updates it.
     * @param query query to match
     * @param fields fields to be returned
     * @param sort sort to apply before picking first document
     * @param remove if true, document found will be removed
     * @param update update to apply
     * @param returnNew if true, the updated document is returned, otherwise the old document is returned (or it would be lost forever)
     * @param upsert do upsert (insert if document not present)
     * @return the document
     * @throws MongoException
     */
    public DBObject findAndModify(DBObject query, DBObject fields, DBObject sort, boolean remove, DBObject update, boolean returnNew, boolean upsert)?

?

?

2、数据库、索引

2.1数据库

mongodb中的数据库对应文档,在前面已经介绍可以通过

DB db = mongo.getDB("sample");

来实例一个数据库对象,如果当然Mongo实例没有该数据库会默认创建一个。此外还提供了一些方法操作数据库:

//获取当前mongo实例创建后所有数据库,可能包括在客户端创建而服务端不存在的数据库(数据库开始在客户端不存在)
public Collection<DB> getUsedDatabases();

//返回服务端所有数据库名字
public List<String> getDatabaseNames();

//删除指定数据库
public void dropDatabase(String dbName);

当然对于数据库,删除也可以通过DB对象方法:

//删除数据库
DB db = mongo.getDB("sample");
db.dropDatabase();
db.command(new BasicDBObject("dropDatabase", 1));

?

2.2索引

在mongo中,我们可以通过以下命令来建立索引:

//对username建立索引
db.smaple.ensureIndex({"username":1})
//对username建立正向索引,age简历反向索引
db.smaple.ensureIndex({"username":1, "age":-1})
//唯一索引
db.smaple.ensureIndex({"username":1},{"unique":true})
//消除重复索引
db.smaple.ensureIndex({"username":1},{"unique":true,"dropDups":true})

在java中也可以通过以下api来做同样的事情:

//创建索引
collection.createIndex(new BasicDBObject("username", 1));
//指定索引名称
collection.ensureIndex(new BasicDBObject("age", -1), "age_index");
//创建唯一索引:如果数据重复将会报错
//com.mongodb.MongoException$DuplicateKey: E11000 duplicate key error index: sample.user.$age_name_index  dup key
collection.ensureIndex(new BasicDBObject("age", -1).append("username", 1), "age_name_index", true);
//根据索引名称删除
collection.dropIndex("username_1");
//删除索引索引
collection.dropIndexes();

?

3、其他

1、索引与执行计划

现在表sample有10w数据内容如下:

{"username":"robin-i", "age":i,"info":{"title":"jee","salary":i}}?

根据条件查询

collection.find(new BasicDBObject("usernam