一、连接到mongodb
二、打开数据库test
获取数据库对象(优先级从高到低):1、构造方法指定2、配置文件指定
构造方法: Mongo mongo = new Mongo("localhost", 27017);
配置文件指定:写好mongo.properties,在工具写好获取对象方法,将属性设置进去,其实还是调用new Mongo()这个构造方法。
public Mongo() { this(new ServerAddress(), createLegacyOptions()); }
public Mongo(String host) { this(new ServerAddress(host), createLegacyOptions()); }
public Mongo(String host, MongoOptions options) { this(new ServerAddress(host), options.toClientOptions()); }
public Mongo(String host, int port) { this(new ServerAddress(host, port), createLegacyOptions()); }
public Mongo(ServerAddress address) { this(address, createLegacyOptions()); }
public Mongo(ServerAddress address, MongoOptions options) { this(address, options.toClientOptions()); }
public Mongo(ServerAddress left, ServerAddress right) { this(Arrays.asList(left, right), createLegacyOptions()); }
public Mongo(ServerAddress left, ServerAddress right, MongoOptions options) { this(Arrays.asList(left, right), options.toClientOptions()); }
public Mongo(List<ServerAddress> seeds) { this(seeds, createLegacyOptions()); }
public Mongo(List<ServerAddress> seeds, MongoOptions options) { this(seeds, options.toClientOptions()); }
public Mongo(MongoURI uri) { this(uri.toClientURI()); }
二、打开数据库test
DB db = mongo.getDB(dbName);
public DB getDB(String dbName) {
DB db = (DB)this.dbCache.get(dbName); //这里用到类似缓存的MAP集合来装你的db数据库
if (db != null) {
return db;
} else {
db = new DB(this, dbName, this.createOperationExecutor()); //调用DB的构造方法
DB temp = (DB)this.dbCache.putIfAbsent(dbName, db); //放到map里了,下次再取这个名字的数据库就有了
return temp != null ? temp : db;
}
}
缓存用的map
private final ConcurrentMap<String, DB> dbCache;
DB的构造方法 只需要name这个参数就行了,executor后台自己调用匿名内部类创建了,不用管。
DB(Mongo mongo, String name, OperationExecutor executor) {
if (!this.isValidName(name)) {
throw new IllegalArgumentException("Invalid database name format. Database name is either empty or it contains spaces.");
} else {
this.mongo = mongo;
this.name = name;
this.executor = executor;
this.collectionCache = new ConcurrentHashMap();
this.optionHolder = new OptionHolder(mongo.getOptionHolder());
this.commandCodec = MongoClient.getCommandCodec();
}
}
三、获取数据库下的集合(类似于mysql的表) 要用上面的db对象来调用
db.getCollection(collName);
public DBCollection getCollection(String name) {
DBCollection collection = (DBCollection)this.collectionCache.get(name);
if (collection != null) {
return collection;
} else {
collection = new DBCollection(name, this, this.executor);
if (this.mongo.getMongoClientOptions().getDbDecoderFactory() != DefaultDBDecoder.FACTORY) {
collection.setDBDecoderFactory(this.mongo.getMongoClientOptions().getDbDecoderFactory());
}
if (this.mongo.getMongoClientOptions().getDbEncoderFactory() != DefaultDBEncoder.FACTORY) {
collection.setDBEncoderFactory(this.mongo.getMongoClientOptions().getDbEncoderFactory());
}
DBCollection old = (DBCollection)this.collectionCache.putIfAbsent(name, collection);
return old != null ? old : collection;
}
}
四、获取集合对象
public List<DBObject> findAll() {
DBCursor cur = getCollection().find(); //collection.find() 查询集合下面的所有对象
List<DBObject> list = new ArrayList<DBObject>();
if (cur != null) {
list = cur.toArray(); //DBCursor 是可以直接转化为list<DBObject>集合的
}
return list;
}
DBCursor对象是有这个方法的
public List<DBObject> toArray() {
return this.toArray(2147483647);
}
public List<DBObject> toArray(int max) {
this.checkIteratorOrArray(DBCursor.IteratorOrArray.ARRAY);
this.fillArray(max - 1);
return this.all;
}
五、插入数据
public void insert(DBObject obj) {
getCollection().insert(obj); //insert(DBObject)
}
public WriteResult insert(DBObject[] documents, WriteConcern writeConcern) { //源码
return this.insert(Arrays.asList(documents), writeConcern);
}
六、批量插入数据
public void insertBatch(List<DBObject> list) {
if (list == null || list.isEmpty()) {
return;
}
List<DBObject> listDB = new ArrayList<DBObject>();
for (int i = 0; i < list.size(); i++) {
listDB.add(list.get(i));
}
getCollection().insert(listDB); //insert(list<DBObject>) DBObject是一个接口
}
调用的是这个方法
public WriteResult insert(List<? extends DBObject> documents) {
return this.insert(documents, this.getWriteConcern());
}
七、删除数据
public void delete(DBObject obj) {
getCollection().remove(obj); //remove(DBObject)
}
public WriteResult remove(DBObject query) {
return this.remove(query, this.getWriteConcern());
}
八、删除多条数据
public void deleteBatch(List<DBObject> list) {
if (list == null || list.isEmpty()) {
return;
}
for (int i = 0; i < list.size(); i++) {
getCollection().remove(list.get(i));
}
}
删除没有批量的方法,并没有remove(List<DBObject>)这类的方法哦
九、获取集合中的数据数量
public long getCollectionCount() {
return getCollection().getCount(); //getCount()
}
十、查找符合条件的数据数量
public long getCount(DBObject obj) {
if (obj != null)
return getCollection().getCount(obj);} //getCount(DBObject)
十一、查找符合条件的数据
public List<DBObject> find(DBObject obj) {
DBCursor cur = getCollection().find(obj);
return DBCursor2list(cur); //这个只是调用DBCursor的toArray方法,将它转化为List<DBObject>集合而已
}
十二、查找符合条件的数据并排序
public List<DBObject> find(DBObject query, DBObject sort) {
DBCursor cur;
if (query != null) {
cur = getCollection().find(query);
} else {
cur = getCollection().find();
}
if (sort != null) {
cur.sort(sort); // <==> getCollection().find(query).sort(sort); } return DBCursor2list(cur); }
十三、查找符合条件的数据并排序,规定数据个数
public List<DBObject> find(DBObject query, DBObject sort, int start, int limit) {
DBCursor cur;
if (query != null) {
cur = getCollection().find(query);
} else {
cur = getCollection().find();
}
if (sort != null) {
cur.sort(sort);
}
if (start == 0) {
cur.batchSize(limit);
} else {
cur.skip(start).limit(limit);
}
return DBCursor2list(cur);
}
十四、更新数据
public void update(DBObject setFields, DBObject whereFields) {
getCollection().updateMulti(whereFields, setFields);
}
十五、由ID获取数据
public DBObject getById(String id) {
DBObject obj = new BasicDBObject();
obj.put("_id", new ObjectId(id));
DBObject result = getCollection().findOne(obj);
return result;
}
调用下列方法
DBObject findOne(DBObject query, DBObject projection, DBObject sort, ReadPreference readPreference, ReadConcern readConcern, long maxTime, TimeUnit maxTimeUnit) {
FindOperation<DBObject> operation = (new FindOperation(this.getNamespace(), this.objectCodec)).readConcern(readConcern).projection(this.wrapAllowNull(projection)).sort(this.wrapAllowNull(sort)).limit(-1).maxTime(maxTime, maxTimeUnit);
if (query != null) {
operation.filter(this.wrap(query)); //wrap() 将DBObject转化为BsonDocument
}
BatchCursor<DBObject> cursor = (BatchCursor)this.executor.execute(operation, readPreference);
return cursor.hasNext() ? (DBObject)cursor.next().iterator().next() : null;
}
--------------------
最新的java操作mongo方法,是获取mongoClient,操作的集合是MongoCollection,而不是DBCollection了。
有个博主总结的不错,直接附上链接
查询 https://blog.csdn.net/autfish/article/details/51366839
操作 https://blog.csdn.net/autfish/article/details/51356537