mac下安装MongoDb
MongoDb初体验
背景:在看了网上N篇教程之后,发现了各种不靠谱,于是开始踏上踩坑Mongo之路。
1. 安装MongoDb3.6 和 Mongod
1.安装
curl -O https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-3.6.2.tgz
2.解压
/opt/soft/mongo/
3.环境变量
vi ~/.bash_profile
export MONGO_PATH=/opt/soft/mongo/mongodb-osx-x86_64-3.6.2
export PATH=$PATH:$MONGO_PATH/bin
source ~/.bash_profile
4.添加Mongo数据库db
mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/data/
mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/data/db
chmod -R 777 /opt/soft/mongo/
5.添加Mongo配置文件
mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/etc
cd etc && touch mongod.conf
#mongodb config file
dbpath=/opt/soft/mongo/mongodb-osx-x86_64-3.6.2/data/db
logpath=/opt/soft/mongo/mongodb-osx-x86_64-3.6.2/logs/mongodb/mongod.log
logappend = true
bind_ip = 127.0.0.1
journal=true
port = 27017
# fork允许后端子进程启动,终端可以随便关
fork = true
# 安全权限,可以先以非授权模式启动Mongod,添加完用户db.addUser('root','pwd') ,再开启auth = true 后,db.auth('root','pwd'),带密码登陆
auth = true
6.添加log文件
mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/logs
mkdir /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/logs/mongodb/
touch mongod.log
2. 起飞
1.启动
mongod --config /opt/soft/mongo/mongodb-osx-x86_64-3.6.2/etc/mongod.conf
2.访问数据库
mongo3.x 之后就没有web控制台了,不要网上搜了,各种帖子都是老掉牙的,建议下载一个mongo客户端,作为操作
https://download.studio3t.com/studio-3t/mac/5.7.3/Studio-3T.dmg
也可以手动再开终端,使用 mongo 命令连接上来,show db 等命令手动增删改查数据库。
9.命令
* 1.终端连接 `mongo`
* 2.查看库 `show dbs`
* 3.创建DB `use demoDb` 使用demoDb(无则创建)
* 4.创建表 `db.democollection.insert({name:"jackMa",age:18})` 自动创建表,并插入一条Json
* 5.查看表 `show collections`
* 6.主键 Every document stored in MongoDB must have an "_id" key, and you can have other keys as many as your wish.Mongo会自动插入一列叫 "_id",可以自己在程序里处理这个字段,插入到Mongo中,达到联合主键的目的,Mongo本身不支持联合主键
* 7.查询 `db.democollection.find({}).limit(1000);`
* 8.js查询
```
let mongodb = require("mongodb");
let client = mongodb.MongoClient;
let url = "mongodb://host:port/msginfo";
client.connect(url, function (err, db) {
let collection = db.collection("msg_phone");
let query = {};
let limit = 1000;
let cursor = collection.find(query).limit(limit);
cursor.forEach(
function(doc) {
console.log(doc["_id"]);
},
function(err) {
db.close();
}
);
});
```
3.Demo
-
Pom
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.2.0</version> </dependency>
-
Test
MongoDb.java
package com.demo.util; import java.util.ArrayList; import java.util.List; 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.result.UpdateResult; import org.bson.Document; import org.bson.conversions.Bson; /** * @author luoyu.lzy * @Title: MongoDb.java * @Package com.demo.util * @Description: * @date 2018/1/17. */ public class MongoDb { private static MongoCollection<Document> collection; /** * 链接数据库 * * @param databaseName * 数据库名称 * @param collectionName * 集合名称 * @param hostName * 主机名 * @param port * 端口号 */ public static void connect(String databaseName, String collectionName, String hostName, int port) { @SuppressWarnings("resource") MongoClient client = new MongoClient(hostName, port); MongoDatabase db = client.getDatabase(databaseName); collection = db.getCollection(collectionName); System.out.println(collection); } /** * 插入一个文档 * * @param document * 文档 */ public static void insert(Document document) { collection.insertOne(document); } /** * 查询所有文档 * * @return 所有文档集合 */ public static List<Document> findAll() { List<Document> results = new ArrayList<Document>(); FindIterable<Document> iterables = collection.find(); MongoCursor<Document> cursor = iterables.iterator(); while (cursor.hasNext()) { results.add(cursor.next()); } return results; } /** * 根据条件查询 * * @param filter * 查询条件 //注意Bson的几个实现类,BasicDBObject, BsonDocument, * BsonDocumentWrapper, CommandResult, Document, RawBsonDocument * @return 返回集合列表 */ public static List<Document> findBy(Bson filter) { List<Document> results = new ArrayList<Document>(); FindIterable<Document> iterables = collection.find(filter); MongoCursor<Document> cursor = iterables.iterator(); while (cursor.hasNext()) { results.add(cursor.next()); } return results; } /** * 更新查询到的第一个 * * @param filter * 查询条件 * @param update * 更新文档 * @return 更新结果 */ public static UpdateResult updateOne(Bson filter, Bson update) { UpdateResult result = collection.updateOne(filter, update); return result; } /** * 更新查询到的所有的文档 * * @param filter * 查询条件 * @param update * 更新文档 * @return 更新结果 */ public static UpdateResult updateMany(Bson filter, Bson update) { UpdateResult result = collection.updateMany(filter, update); return result; } /** * 更新一个文档, 结果是replacement是新文档,老文档完全被替换 * * @param filter * 查询条件 * @param replacement * 跟新文档 */ public static void replace(Bson filter, Document replacement) { collection.replaceOne(filter, replacement); } /** * 根据条件删除一个文档 * * @param filter * 查询条件 */ public static void deleteOne(Bson filter) { collection.deleteOne(filter); } /** * 根据条件删除多个文档 * * @param filter * 查询条件 */ public static void deleteMany(Bson filter) { collection.deleteMany(filter); } }
MongoTest.java
package com.demo.util; import java.util.List; import com.mongodb.client.result.UpdateResult; import org.bson.Document; import org.junit.Before; import org.junit.Test; /** * @author luoyu.lzy * @Title: MongoTest.java * @Package com.demo.util * @Description: * @date 2018/1/17. */ public class MongoTest { @Before public void before() { MongoDb.connect("dbName", "collectionName", "127.0.0.1", 27017); } @Test public void testInsert() { Document document = new Document(); document.append("name", "wang").append("gender", "female"); MongoDb.insert(document); } @Test public void testFindAll() { List<Document> results = MongoDb.findAll(); for (Document doc : results) { System.out.println(doc.toJson()); } } @Test public void testFindBy() { Document filter = new Document(); filter.append("name", "li si"); List<Document> results = MongoDb.findBy(filter); for (Document doc : results) { System.out.println(doc.toJson()); } } @Test public void testUpdateOne() { Document filter = new Document(); filter.append("gender", "male"); //注意update文档里要包含"$set"字段 Document update = new Document(); update.append("$set", new Document("gender", "female")); UpdateResult result = MongoDb.updateOne(filter, update); System.out.println("matched count = " + result.getMatchedCount()); } @Test public void testUpdateMany() { Document filter = new Document(); filter.append("gender", "female"); //注意update文档里要包含"$set"字段 Document update = new Document(); update.append("$set", new Document("gender", "male")); UpdateResult result = MongoDb.updateMany(filter, update); System.out.println("matched count = " + result.getMatchedCount()); } @Test public void testReplace() { Document filter = new Document(); filter.append("name", "zhang"); //注意:更新文档时,不需要使用"$set" Document replacement = new Document(); replacement.append("value", 123); MongoDb.replace(filter, replacement); } @Test public void testDeleteOne() { Document filter = new Document(); filter.append("name", "li"); MongoDb.deleteOne(filter); } @Test public void testDeleteMany() { Document filter = new Document(); filter.append("gender", "male"); MongoDb.deleteMany(filter); } }