插入数据
db.comment.insert(
{"articleid":"100000","content":"今天天气真好,阳光明媚","userid":"1001",
"nickname":"Rose","age":"20","phone":"18807141995","createdatetime":new Date(),
"likenum":NumberInt(10),"state":null}
)
db.comment.insertMany([{"_id":"1","articleid":"100001","content":"清晨,我们不该把事件浪费在手机上,健康很重要,喝一杯温水,幸福你我他。","userid":"1002","nickname":"相忘于江湖","age":"25","phone":{"homePhone":"82174911","mobilePhone":"13065840128"},"createdatetime":new Date("2020-01-02 09:08:15"),"likenum":NumberInt(1000),"state":"1"},{"_id":"2","articleid":"100001","content":"我夏天空腹喝凉开水,冬天喝温开水","userid":"1003","nickname":"伊人憔悴","age":"22","phone":"13442031624","createdatetime":new Date("2020-01-02 10:20:40"),"likenum":NumberInt(888),"state":"1"},{"_id":"3","articleid":"100001","content":"夏天和冬天,我都喝凉开水","userid":"1004","nickname":"杰克船长","age":"28","phone":"1393716334","createdatetime":new Date("2020-01-02 19:56:09"),"likenum":NumberInt(666),"state":null},{"_id":"4","articleid":"100001","content":"专家说不能空腹喝冰水,影响健康","userid":"1005","nickname":"罗密欧","age":"18","phone":"15813134403","createdatetime":new Date("2020-01-03 11:26:29"),"likenum":NumberInt(2000),"state":"1"},{"_id":"5","articleid":"100001","content":"研究表明,刚烧开的水千万不要喝,因为烫嘴","userid":"1005","nickname":"罗密欧","age":"18","phone":"15813134403","createdatetime":new Date("2020-01-03 15:10:37"),"likenum":NumberInt(3000),"state":"1"},{"_id":"6","articleid":"100001","content":"喝水是生命体通过口腔摄入水分的方式,人体每天通过口腔摄入的液体大概有2升","userid":"1006","nickname":"爱德华","age":"30","phone":{"homePhone":"62771541","mobilePhone":"13262984142"},"createdatetime":new Date("2020-01-03 15:10:37"),"likenum":NumberInt(3000),"state":"1"}
])
更新数据
db.comment.update({"content":"喝水是生命体通过口腔摄入水分的方式,人体每天通过口腔摄入的液体大概有2升"},{$set:{"content":"喝水增加了尿量,能使有害物质及时排出体内"}})
文档查询
#按条件查询文档
db.comment.find({$and:[{"userid":"1005","nickname":"罗密欧"}]}).pretty()
db.comment.find({$or:[{"userid":"1002","userid":"1003"}]}).pretty()
db.comment.find({"userid":{$gt:"1005"}}).pretty()
db.comment.find({"userid":{$lt:"1004"}}).pretty()
db.comment.find({"userid":{$gte:"1005"}}).pretty()
db.comment.find({"userid":{$lte:"1003"}}).pretty()
db.comment.find({"userid":{$ne:"1005"}}).pretty()
db.comment.find({"_id":{$in:["1","3"]}}).pretty()
db.comment.find({"_id":{$nin:["1","3","5"]}}).pretty()
#按特定类型查询文档
db.comment.find({"state":null}).pretty()
db.comment.find({"content":/^专家/}).pretty()
db.comment.find({"phone":{"homePhone":"62771541","mobilePhone":"13262984142"}}).pretty()
db.comment.find({"phone.homePhone":"82174911"}).pretty()
聚合管道操作
db.comment.aggregate([{$group:{"_id":"$userid"}}]).pretty()
db.comment.aggregate({$limit:3}).pretty()
db.comment.aggregate([{$match:{"nickname":"罗密欧"}}]).pretty()
db.comment.aggregate([{$sort:{"age":-1}}]).pretty()
db.comment.aggregate([{$project:{"_id":0}}]).pretty()
db.comment.aggregate({$skip:4}).pretty()
#创建一个集合product
db.createCollection("product")
show collections
db.product.insertMany([
{"_id":"1","name":"iPhone8","price":3000,"type":"电子通信"},
{"_id":"2","name":"adidas neo","price":700,"type":"服装"},
{"_id":"3","name":"nike air max 90","price":760,"type":"服装"},
{"_id":"4","name":"HuaWei mate30","price":5000,"type":"电子通信"},
{"_id":"5","name":"vivo x27","price":2000,"type":"电子通信"},
])
db.product.aggregate([{$group:{"_id":"$type","price":{$sum:"$price"}}}]).pretty()
db.product.aggregate([{$group:{"_id":"$type","price":{$avg:"$price"}}}]).pretty()
db.product.aggregate([{$group:{"_id":"$type","price":{$min:"$price"}}}]).pretty()
db.product.aggregate([{$group:{"_id":"$type","price":{$max:"$price"}}}]).pretty()
db.product.aggregate([{$group:{"_id":"$type","tags":{$push:"$price"}}}]).pretty()
db.product.aggregate([{$group:{"_id":"$type","product":{$first:"$name"}}}]).pretty()
db.product.aggregate([{$group:{"_id":"$type","product":{$last:"$name"}}}]).pretty()
Map-Reduce操作
db.comment.mapReduce(
function(){emit(this.nickname,1);},
function(key,values){return Array.sum(values)},
{
query:{state:"1"},
out:"comment_total"
}
)
db.comment_total.find()
索引操作
#查看索引
db.comment.getIndexes()
#查看索引大小
db.comment.totalIndexSize()
#创建索引
db.comment.createIndex({userid:1})
db.comment.getIndexes()
db.comment.createIndex({userid:1,nickname:-1})
db.comment.getIndexes()
#删除索引
db.comment.dropIndex({userid:1})
db.comment.getIndexes()
db.comment.createIndex({userid:1})
db.comment.dropIndexes()
db.comment.getIndexes()
这是我的Java版本、IDEA版本:
添加Maven至IDEA工具中:File–>Settings
Maven把一个项目的结构和内容抽象成一个模型,在xml文件中进行声明,以方便进行构建和描述,pom.xml是Maven的灵魂。
配置项目nosql_chapter03中的pom.xml文件(引入MongoDB相关的依赖和单元测试的依赖):
添加的内容如下:
<dependencies>
<!--单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--Java操作mongoDB的驱动依赖-->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.1</version>
</dependency>
</dependencies>
如果没有自动加载相关依赖,可以右键–>Maven–>Reload project一下重新加载,如遇到相关无法自动加载问题可参考:解决idea中maven项目的pom文件不会自动下载jar包问题 + 更新不完整依赖命令/CSDN@程序猿秃头之路
在项目nosql_chapter03的目录/src/main/resources下创建一个名为mongodb.properties文件,用于存储连接MongoDB数据库所需要的参数
host = 192.168.121.134 //主机IP地址,127.0.0.1
port = 27017 //端口号
dbname = articled //要操作的MongoDB数据库名称
在项目nosql_chapter3目录/src/test/java下创建一个名为com.itcast.mongodb包,并在该包下创建MongoUtils.java文件,该文件用于编写Java连接MongoDB数据库的工具类。
package com.itcast.mongodb;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MongoUtils {
private static Properties properties;
private static MongoDatabase mongoDatabase;
private static String host;
private static int port;
private static InputStream stream = null ;
private static String dbname;
//创建一个静态代码块,用于初始化工具类中的静态变量,该静态代码块在类的加载过程中初始化阶段执行而且只执行一次
static{
if (properties == null){
//判断properties对象是否为空,空则new一个出来
properties = new Properties();
}
try {
//创建字节流输入对象用来接受配置文件中的参数
stream = MongoUtils.class.getClassLoader().getResourceAsStream("mongodb.properties");
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
host = properties.getProperty("host");
port = Integer.parseInt(properties.getProperty("port"));
dbname = properties.getProperty("dbname");
}
//定义一个getMongoClient方法,用来获取数据库连接对象
public static com.mongodb.client.MongoClient getMongoClient(){
String addr = "mongodb://"+host+":"+port;
return MongoClients.create(addr);
}
//定义一个getMongoConn方法,用来实现连接指定的mongo数据库
public static MongoDatabase getMongoConn(){
MongoClient mongoClient = getMongoClient();
mongoDatabase = mongoClient.getDatabase(dbname);
return mongoDatabase;
}
}
11-14行:声明连接MongoDB所需要的成员对象和成员变量
17-39行:创建一个静态代码块–>初始化工具类中的静态变量
41-46行:定义getMongoClient()方法–>获取MongoDB数据库的连接对象,即MongoClient
49-52行:定义getMongoConn()方法–>连接指定的MongoDB数据库
注意运行测试类时NoSQL处于打开状态
在项目nosql_chapter3目录/src/test/java下创建一个名为TestMongo.java的文件,该文件用于编写Java连接并操作MongoDB数据库的测试类。
运行测试类前的数据库:
import com.itcast.mongodb.MongoUtils;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.junit.Test;
import java.util.Date;
public class TestMongo{
private static MongoDatabase mongoDatabase;
public static void main(String[] args){
mongoDatabase = MongoUtils.getMongoConn();
}
}
在TestMongo.java中,定义一个getDBs()方法,用于查看MongoDB中的所有数据库。
@Test
@Test
public void getDBs(){
MongoClient mongoClient = MongoUtils.getMongoClient();
MongoIterable<String>databaseNames = mongoClient.listDatabaseNames();
for(String databaseName : databaseNames){
System.out.println(databaseName);
}
}
在TestMongo.java中,定义一个getCollection()方法,用于查看数据库articledb中的集合。
@Test
public void getCollection(){
mongoDatabase = MongoUtils.getMongoConn();
MongoIterable<String>listCollectionNames = mongoDatabase.listCollectionNames();
for(String collectionName : listCollectionNames){
System.out.println(collectionName.toString());
}
}
在TestMongo.java中,定义一个createCollection()方法,用于创建集合itcast。
@Test
public void createCollection(){
mongoDatabase = MongoUtils.getMongoConn();
mongoDatabase.createCollection("itcast");
}
在TestMongo.java中,定义一个dropCollection()方法,用于删除集合itcast。
@Test
public void dropCollection() {
mongoDatabase = MongoUtils.getMongoConn();
MongoCollection<Document> itcast = mongoDatabase.getCollection("itcast");
itcast.drop();
}
在TestMongo.java中,定义一个findDocument()方法,用于查看文档,即查看集合comment中的文档。
@Test
public void findDocument(){
mongoDatabase = MongoUtils.getMongoConn();
MongoCollection<Document>comment = mongoDatabase.getCollection("comment");
FindIterable<Document>documents = comment.find();
for(Document document : documents){
System.out.println(document);
}
}
在TestMongo.java中,定义一个insertOneDocument()方法,用于插入单个文档,即在集合comment中插入一个文档。
@Test
public void insertOneDocument(){
mongoDatabase = MongoUtils.getMongoConn();
MongoCollection<Document>comment = mongoDatabase.getCollection("comment");
Document document = new Document("_id","7").append("articleid","100001")
.append("content","吃饭前,先喝杯水或一碗汤,可减少饭量,对控制体重有帮助")
.append("userid","1007")
.append("nickname","玛丽莲·梦露")
.append("age","18")
.append("phone","13937165554")
.append("createdatetime",new Date())
.append("likenum","8888")
.append("state","null");
comment.insertOne(document);
}
在TestMongo.java中,定义一个updateDocument()方法,用于更新文档,即更新集合comment中的文档。
@Test
public void updateDocument(){
mongoDatabase = MongoUtils.getMongoConn();
MongoCollection<Document>comment = mongoDatabase.getCollection("comment");
Document document = new Document("content","饭后半小时最好不要喝大量的水,以免冲淡胃液,稀释胃酸,损害消化功能");
comment.updateOne(Filters.eq("content","吃饭前,先喝杯水或一碗汤,可减少饭量,对控制体重有帮助"),new Document("$set",document));
}
在TestMongo.java中,定义一个deleteDocument()方法,用于删除文档,即删除集合comment中的文档。
@Test
public void deleteDocument(){
mongoDatabase = MongoUtils.getMongoConn();
MongoCollection<Document>comment = mongoDatabase.getCollection("comment");
comment.deleteOne(Filters.eq("_id","7"));
}
注意测试时打开MongoDB
分开测试也行,下面写进一个.py文件:
from pymongo import MongoClient
class Test:
def __init__(self):
self.client=MongoClient('127.0.0.1',27017)
print(self.client)
#查看数据库
def getDBs(self):
dbs=self.client.list_database_names()
for db in dbs:
print(db)
#查看集合
def getColl(self):
articledb=self.client["articledb"]
collections=articledb.list_collection_names()
for collections in collections:
print(collections)
#创建集合
def createColl(self):
articledb=self.client["articledb"]
articledb.create_collection("itcast")
#删除集合
def dropColl(self):
articledb = self.client["articledb"]
articledb.drop_collection("itcast")
#查看文档
def findDoc(self):
self.articledb=self.client["articledb"]
comment=self.articledb["comment"]
documents=comment.find()
for document in documents:
print(document)
#插入文档
def insertOneDoc(self):
self.articledb=self.client["articledb"]
comment=self.articledb["comment"]
newDoc={
"_id":"7",
"articleid":"100001",
"content":"脱水会使人精疲力尽,而喝水可以使人精神饱满",
"userid": "1007",
"nickname": "咫尺天涯间",
"age": "25",
"phone": "13937165554",
"createdatetime": "new Date()",
"likenum": "999",
"state": "1"
}
comment.insert_one(newDoc)
#更新文档
def updateDoc(self):
self.articledb=self.client["articledb"]
comment=self.articledb["comment"]
comment.update_one({"content":"脱水会使人精疲力尽,而喝水可以使人精神饱满"},{"$set":{"content":"吃饭前,先喝一杯水或一碗汤,可减少饭量,对控制体重有明显帮助"}})
#删除文档
def deleteDoc(self):
self.articledb = self.client["articledb"]
comment = self.articledb["comment"]
comment.delete_one({"nickname":"咫尺天涯间"})
if __name__=='__main__':
test=Test()
# 每次运行解除一条注释即可
# test.getDBs()
# test.getColl()
# test.createColl()
# test.dropColl()
# test.findDoc()
# test.insertOneDoc()
# test.updateDoc()
# test.deleteDoc()
注意运行时打开MongoDB
右击“New Connection”–>“Create Database”
右击数据库“itcase”–>“Drop Database”
{
"_id":"7",
"articleid":"100001",
"content":"下午两三点的时候,冲一杯绿茶给自己,既提神醒脑,又能抵抗辐射",
"userid":"1007",
"nickname":"超甜的布丁",
"age":"20",
"phone":"13837361114",
"createdatetime":"new Date()",
"likenum":"222",
"state":"null"
}
没有同步的话刷新一下
db.getCollection('comment').update(
// query
{
"content":"下午两三点的时候,冲一杯绿茶给自己,既提神醒脑,又能抵抗辐射"
},
// update
{
$set:{"content":"吃饭前,先喝一杯水或一碗汤,可减少饭量,对控制体重有明显的帮助"}
},
// options
{
"multi" : false, // update only one document
"upsert" : false // insert a new document, if no existing document match the query
}
);
为了提高MongoDB数据库中数据的安全性,需要开启用户访问控制(即用户验证),否则每个人都可以访问数据
MongoShell是这个:
db.createUser({user:"itcastAdmin",pwd:passwordPrompt(),roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
在MongoDB未对用户分配角色之前,用户是无法链接并访问MongoDB的,因此做以下配置:
我的路径为:D:\mongodb\conf\mongod.conf
然后重启MongoDB
db.auth("itcastAdmin",passwordPrompt())
3.【NoSQL数据库技术与应用】-- MongoDB数据库操作/CSDN@⚆Pearl
5.idea2020.1配置maven/CSDN@淡忘_Java
7.【Maven】pom.xml教程/CSDN@Hackyle