window版本2.0.2下载地址:http://downloads.mongodb.org/win32/mongodb-win32-i386-2.0.2.zip
免安装直接解压ok
启动mongodb
进入%MONGODB_HOME%\bin
主要用到两个文件:mongod,mongo
mongod用来启动mongo
mongo即mongodb的命令行工具
执行mongod.exe --port=8083 --directoryperdb --logpath=.\mongodb.log --logappend
mongod.exe相关参数
port指定端口号
directortyperdb指定每个db创建一个单独的文件
logpath指定日志文件位置
logappend指定日志是追加还是覆盖
bind_ip指定ip地址
屏幕没有报错说明启动成功
命令行连接mongodb
执行mong.exe
出现如下错误Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84 connection fail
我们指定了端口号,所以需要加入端口号参数
mongo.exe --port=8083
显示如下
MongoDB shell version: 2.0.2
connecting to: 127.0.0.1:8083/test
>
边接成功
命令行下输入use test
表示使用test库
如果输入use test1创建test1库并进入
查看所有用户
show users
查看所有表
show collections
添加用户
db.addUser("test","test")
创建新表
db.createCollection("tableName")
删除表
db.collectionName.drop()
插入数据
db.collectionName.save({hello:1,world:2})
查询表数据
db.collectionName.find()
java操作mongodb
jar下载地址:https://github.com/downloads/mongodb/mongo-java-driver/mongo-2.7.3.jar
创建工程并引用jar
import java.net.UnknownHostException;
import java.util.List;
import java.util.Set;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.WriteResult;
public class HelloMongo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Mongo mongo = new Mongo("localhost", 8083);
List<String> dbList = mongo.getDatabaseNames();
for (String s : dbList) {
System.out.println(s);
}
DB db = mongo.getDB("mydb");
Set<String> colSet = db.getCollectionNames();
for (String s : colSet) {
System.out.println(s);
}
String[] myStr = { "aa", "bb", "cc" };
DBCollection myColl = db.getCollection("mycoll");
DBObject obj = new BasicDBObject();
obj.put("javaTest", myStr);
myColl.save(obj);
obj.put("hello", 1.0);
DBCursor cursor=myColl.find();
while(cursor.hasNext()){
System.out.println(cursor.next());
}
DBObject queryCon=new BasicDBObject();
queryCon.put("hello", 1.0);
WriteResult result=myColl.remove(queryCon);
System.out.println(result.getN());
mongo.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MongoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}