mongodb安装与使用

一、在linux服务器中安装mongodb

1.首先你要有一台安装有linux系统的主机

2.从mongoDB官网下载安装包:http://www.mongodb.org/downloads

3.将下载的.tgz安装包上传到指定的目录下,我长传在/usr/local/mongod/目录下

4.linux创建目录已经上传.tgz文件命令如下:

pwd // 查看当前目录

cd /     // 进入根目录

cd /usr/local/    // 进入usr/local目录下

mkdir mongod  //创建mongod文件夹

cd /usr/local/mongod/   // 进入mongod文件目录下

rz -e  // 上传文件命令

tar -zxvf 上传的安装文件名

mkdir -p /data/db  // 创建mongodb默认启动数据库路径

5.进入安装mongodb安装文件解压后的文件bin目录下,输入一下命令:

./ mongod  // 启动服务

ps -ef|grep mongod  // 查看启动的mongodb进程

./ mongo  // 启动连接

出现如下提示:说明启动成功!

6.mongodb常用命令

mongodb数据存储是一种类json格式的数据存储,Bson类型,存储内容的_id字段的内容是mongodb本身算法获取是唯一 。

>use datebase // 使用指定数据库

>db.help()  // 帮助

>db.stats()

>db.version() // 查看数据库版本

>db.collection.insert({username:'ablejava',password:123}) // 插入数据

>db.collection.find();  db.colloection.find({name:'iphone'})// 查询数据

>db.collection.findOne({name:'iphone'});// 返回满足条件集合的第一条。

7.范围条件查询

关键字: $gt  $lt  $gte  $lte

mysql关键字:>   <   >=   <=

db.goods.find({price:{"$gt":1005}})  // 查询价格大于1500的商品

db.goods.find({price:{'$gt':1000},weight:{'$lt':50}})  // 价格大于1000并且重量小于50的

db.goods.find({color:'red'}) // 数组元素值有val即可(存在一个元素),查询颜色有红色记录条数,满足一个元素即可

db.goods.find({type:{'$all':[v1,v2]}}) //查询数组元素值,同时存在v1和v2即可(v1,v2顺序不做要求)(存在多个元素) 

db.goods.find('$or':[{price:2000},{number:{'$lt':100}}]); // 价格大于2000或者number小于200的

限制查询:

db.表.find({条件},{字段:1/0,字段:1/0})

1:查询此字段

0:排除此字段

db.goods.find({price:2000},{name:1,_id:0}) // 查询价格大于2000并且只显示name字段

就是要输出就全部输出,要不输出就全部不输出。_id除外,可以随意设置0,1.

要其中一个字段设置为1,其中一个字段设置为0会报错。

db.goods.update({name:'xiaomi5'},{'$set':{name:'xiaomi5s'}})

没有$set,没有修改的字段就删除了,除id

db.goods.remove({name:'小米'}) // 删除一条记录

db.goods.update({name:'huawei'},{'$unset':{name:0}}) // 删除记录

二、mongodb在java中的使用

1.首先下载mongodb所需要的jar包,新建一个项目将所需要的jar添加到项目中

2.连接数据库,创建集合,获取集合

package com.my.test;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Test {
	public static void main(String[] args) {
		MongoClient mongoClient = null;
		 try{   
			 // 连接到 mongodb 服务
			 mongoClient = new MongoClient( "192.168.9.235" , 27017 );
			 // 连接到数据库
			 MongoDatabase mongoDatabase = mongoClient.getDatabase("test");  
			 System.out.println("连接数据库成功!");
// 创建集合 mongoDatabase.createCollection("col"); System.out.println("创建集合成功!");
// 获取集合 MongoCollection<Document> collection = mongoDatabase.getCollection("col"); System.out.println("获取集合成功!"); }catch(Exception e){ System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } finally { if (mongoClient != null) { mongoClient.close(); } } } }

如果连接mongodb数据库需要用户名和密码,使用下边的连接方式:

package com.my.test;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Test {	
	 public static void main(String[] args){  
	        try {  
	            //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址  
	            //ServerAddress()两个参数分别为 服务器地址 和 端口  
	            ServerAddress serverAddress = new ServerAddress("localhost",27017);  
	            List<ServerAddress> addrs = new ArrayList<ServerAddress>();  
	            addrs.add(serverAddress);  
	              
	            //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码  
	            MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());  
	            List<MongoCredential> credentials = new ArrayList<MongoCredential>();  
	            credentials.add(credential);  
	              
	            //通过连接认证获取MongoDB连接  
	            MongoClient mongoClient = new MongoClient(addrs,credentials);  
	              
	            //连接到数据库  
	            MongoDatabase mongoDatabase = mongoClient.getDatabase("databaseName");  
	            System.out.println("Connect to database successfully");  
	        } catch (Exception e) {  
	            System.err.println( e.getClass().getName() + ": " + e.getMessage() );  
	        }  
	    }

}

3.插入文档,删除文档,查询文档,修改文档

package com.my.test;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;

public class Test {
	public static void main(String[] args) {
		MongoClient mongoClient = null;
		 try{   
			 // 连接到 mongodb 服务
			 mongoClient = new MongoClient( "192.168.9.235" , 27017 );
			 // 连接到数据库
			 MongoDatabase mongoDatabase = mongoClient.getDatabase("mycol");  
			 System.out.println("Connect to database successfully");
			 mongoDatabase.createCollection("col2");
			 System.out.println("创建集合成功!");
			 MongoCollection<Document> collection = mongoDatabase.getCollection("test2");
			 System.out.println("获取集合成功!");
			//插入文档  
	         /** 
	         * 1. 创建文档 org.bson.Document 参数为key-value的格式 
	         * 2. 创建文档集合List<Document> 
	         * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document) 
	         * */
	         Document document = new Document(); 
	         document.append("description", "mongodb"); 
	         document.append("likes", 100);  
	         document.append("by", "Fly");
	         Document document2 = new Document();  
	         document2.append("description", "redis"); 
	         document2.append("likes", 100);  
	         document2.append("by", "Fly");
	         
	         List<Document> documents = new ArrayList<Document>();  
	         documents.add(document); 
	         documents.add(document2);
	         collection.insertMany(documents);  
	         System.out.println("文档插入成功");
	         //检索所有文档  
	         /** 
	         * 1. 获取迭代器FindIterable<Document> 
	         * 2. 获取游标MongoCursor<Document> 
	         * 3. 通过游标遍历检索出的文档集合 
	         * */  
	         FindIterable<Document> findIterable = collection.find();  
	         MongoCursor<Document> mongoCursor = findIterable.iterator();  
	         while(mongoCursor.hasNext()){  
	            System.out.println(mongoCursor.next());  
	         }
		      
	         //更新文档   将文档中likes=100的文档修改为likes=200   
	         collection.updateMany(Filters.eq("likes", 100), new Document("$set",new Document("likes",200)));  
	         //检索查看结果  
	         FindIterable<Document> findIterableUpdate = collection.find();  
	         MongoCursor<Document> mongoCursorUpdate = findIterableUpdate.iterator();  
	         while(mongoCursorUpdate.hasNext()){  
	            System.out.println(mongoCursorUpdate.next());  
	         } 
	         
	         //删除符合条件的第一个文档  
	         collection.deleteOne(Filters.eq("likes", 200));  
	         //删除所有符合条件的文档  
	         collection.deleteMany (Filters.eq("likes", 200));  
	         //检索查看结果  
	         FindIterable<Document> findIterableDel = collection.find();  
	         MongoCursor<Document> mongoCursorDel = findIterableDel.iterator();  
	         while(mongoCursorDel.hasNext()){  
	           System.out.println(mongoCursorDel.next());  
	         }  
		 }catch(Exception e){
			 System.err.println( e.getClass().getName() + ": " + e.getMessage() );
		 } finally {
			 if (mongoClient != null) {
				 mongoClient.close();
			}
		 }

源码下载,客户端工具下载,使用手册下载:https://github.com/ablejava/mongodb

原文地址:https://www.cnblogs.com/ablejava/p/5667953.html