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); } }