mongoDB学习笔记

本文详细介绍了MongoDB在Windows环境下的启动方法,包括bin目录结构、启动服务及HTTP服务器的基本概念。同时,提供了MongoDBShell的使用方法,并深入探讨了基本CRUD操作,包含数据库、集合和文档的管理,以及查询、保存、删除和更新数据的方法。

一、windows环境下的启动

bin目录结构:


启动mongDB服务:

bin\mongod.exe。默认使用c:\data\db作为数据目录,可在启动时通过dbpath参数指定数据目录:bin\mongod.exe --dbpath=data/db。默认使用27017端口。

mongoDB还会启动一个非常基本的HTTP服务器,监听数字比主端口号高1000的端口,28017端口。可通过浏览器访问http://localhost:28017/来获取数据库的管理信息。

mongoDB Shell:

mongoDB自带一个Javascript Shell,可以从命令行与mongoDB实例交互。启动方式:bin\mongo.exe

会在相对路径data/db中创建相应的数据文件。

二、基本概念

1、文档:

多个键及其关联的值有序地放置在一起便是文档。每种编程语言表示文档的方式不太一样,但大多数语言都有相通的一种数据结构,比如映射、散列或字典。例,在javascript中,文档表示为对象:{"greeting":"hello world!"},JSON格式

2、集合:

集合就是一组文档。如果说mongDB中的文档类似于关系型数据库中的行,那么集合就如同表

3、数据库:

多个文档组成集合,同样多个集合组成数据库。一个mongoDB实例可以承载多个数据库,它们之间可视为完全独立的。

三、基本shell命令

(1)show dbs:查询所有数据库

> show dbs;
egDB    0.0625GB
local   0.03125GB
>
(2)use xx:选择使用某个数据库

> use egDB
switched to db egDB
>
(3)show collections:显示当前所选择的数据库的所有集合

> show collections
student
system.indexes
(4)查询集合中的数据

> db.student.find();
{ "_id" : ObjectId("5221678247f0052b96663e45"), "name" : "eg366" }
四、基本CRUD操作

private static final String host = "192.168.10.100";
private static final int port = 27017;

@Test
public void showDB() throws UnknownHostException {
	Mongo connection = ConnectionUtil.getInstance(host, port);
	List<String> dbs = connection.getDatabaseNames();
	for (String db : dbs) {
		System.out.println(db);
	}
}

@Test
public void dropCollection() throws UnknownHostException {
	Mongo connection = ConnectionUtil.getInstance(host, port);
	DB db = connection.getDB("test");
	DBCollection collection = db.getCollection("blog.type");
	collection.drop();
}

@Test
public void dropDB() throws UnknownHostException {
	Mongo connection = ConnectionUtil.getInstance(host, port);
	DB db = connection.getDB("egDB");
	db.dropDatabase();
}

@Test
public void createDB() {
	System.out.println("############ createDB() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		connection.getDB("egDB");
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void saveStudent() {
	System.out.println("############ saveStudent() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		students.save(new BasicDBObject().append("name", "eg366"));
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void insertStudent() {
	System.out.println("############ insertStudent() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		/* 方式1 */
		students.insert(new BasicDBObject("name", "lala366").append("age", 26).append("createTime", new Date()));
		/* 方式2 */
		BasicDBObject obj = new BasicDBObject();
		obj.put("name", "zhangsan");
		obj.put("age", 30);
		obj.put("createTime", new Date());
		students.insert(obj);
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void insertStudentList() {
	System.out.println("############ insertStudentList() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		List<DBObject> list = new ArrayList<DBObject>();
		list.add(new BasicDBObject("name", "lisi").append("age", 32).append("createTime", new Date()));
		list.add(new BasicDBObject("name", "wangwu").append("age", 16).append("createTime", new Date()));
		int insertCount = students.insert(list).getN();
		System.out.println("insertStudentList count:" + insertCount);
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void deleteStudent() {
	System.out.println("############ deleteStudent() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		int removeCount = students.remove(new BasicDBObject("name", "eg366")).getN();
		System.out.println("deleteStudent count:" + removeCount);
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void updateStudent1() {
	System.out.println("############ updateStudent1() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		/* 根据ID更新 */
		/* 此种做法是错误的,根据ID查询到的对象将会被替换为一个新的对象,用该用$set的方式 */
//			WriteResult wr = students.update(new BasicDBObject("_id", new ObjectId("52216efb47f0801f6618da1a")),
//					new BasicDBObject("age", 26).append("createTime", new Date()));
		WriteResult wr = students.update(new BasicDBObject("_id", new ObjectId("5221765f47f0b93d273f68c9")),
				new BasicDBObject("$set", new BasicDBObject("age", 26).append("createTime", new Date())));
		System.out.println("Error: " + wr.getError());
		System.out.println("update count: " + wr.getN());
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void updateStudent2() {
	System.out.println("############ updateStudent2() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		/* 先查询数据再根据ID更新数据 */
		DBCursor cursor = students.find(new BasicDBObject("name", "lisi"));
		if (cursor.count() == 1) {
			while (cursor.hasNext()) {
				DBObject q = cursor.next();
				students.update(q, new BasicDBObject("$set", new BasicDBObject("lastUpdateTime", new Date())));
			}
		}
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void updateStudent3() {
	System.out.println("############ updateStudent3() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		/* 更新年龄大于等于30的数据 */
		students.update(new BasicDBObject("age", new BasicDBObject("$gte", 30)), new BasicDBObject("$set",
				new BasicDBObject("lastUpdateTime", new Date())));
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void findAllStudent() {
	System.out.println("############ findStudent() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		List<DBObject> list = students.find().toArray();
		for(DBObject obj : list) {
			System.out.println(obj);
		}
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

/**
 * 游标查询
 */
@Test
public void findAllStudentByCursor() {
	System.out.println("############ findAllStudentByCursor() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		DBCursor cursor = students.find();
		System.out.println("count:" + cursor.count());
		while(cursor.hasNext()) {
			DBObject obj = cursor.next();
			System.out.println("_id:" + obj.get("_id") + ";age" + obj.get("age") + ";createTime"
					+ obj.get("createTime"));
		}
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void find01() {
	System.out.println("############ find01() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		/* 查询(age in (26,32))的数据;QueryOperators.IN,QueryOperators.NIN */
		List<DBObject> list = students.find(
				new BasicDBObject("age", new BasicDBObject(QueryOperators.IN, new int[] { 26, 32 }))).toArray();
		System.out.println("count:" + list.size());
		for(DBObject obj : list) {
			System.out.println(obj);
		}
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void findOrder() {
	System.out.println("############ findOrder() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		/* 按照年龄大小倒序排;1:正序;-1:倒序 */
		List<DBObject> list = students.find().sort(new BasicDBObject("age", -1)).toArray();
		for(DBObject obj : list) {
			System.out.println(obj);
		}
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

/**
 * 只查询age字段
 */
@Test
public void findOnlyAge() {
	System.out.println("############ findOnlyAge() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		/* find(DBObject ref, DBObject keys) */
		List<DBObject> list = students.find(null, new BasicDBObject("age", true)).toArray();
		for (DBObject obj : list) {
			System.out.println(obj);
		}
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

/**
 * 根据age查询条件查询年龄>=10的数据,只查取这些数据的name字段
 */
@Test
public void findOnlyNameByAge() {
	System.out.println("############ findOnlyNameByAge() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		/* find(DBObject ref, DBObject keys) */
		List<DBObject> list = students.find(new BasicDBObject("age", new BasicDBObject("$gte", 10)),
				new BasicDBObject("name", true)).toArray();
		for (DBObject obj : list) {
			System.out.println(obj);
		}
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}

@Test
public void find02() {
	System.out.println("############ find02() #############");
	try {
		Mongo connection = ConnectionUtil.getInstance(host, port);
		DB db = connection.getDB("egDB");
		DBCollection students = db.getCollection("student");
		System.out.println("findOne: " + students.findOne());

		System.out.println("findOne: " + students.findOne(new BasicDBObject("age", 26)));

		System.out.println("findOne: "
				+ students.findOne(new BasicDBObject("age", 26), new BasicDBObject("name", true)));
	} catch (UnknownHostException e) {
		e.printStackTrace();
	}
}


网上查,针对mongodb实现orm方案有Morphia、spring data方式。待使用时调研

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值