6.29MongoDB之"改"

MongoDB之"改"

MongoDB插入文档

文档的格式:

  • 文档的数据结构和 JSON 基本一样。

  • 所有存储在集合中的数据都是 BSON 格式。

  • BSON 是一种类似 JSON 的二进制形式的存储格式,是 Binary JSON 的简称。

方法:

  • insert()--->若插入的数据主键已经存在,则会抛 org.springframework.dao.DuplicateKeyException (sprintboot框架的异常)异常,提示主键重复,不保存当前数据。

  • save()--->该方法新版本中已废弃,可以使用 db.collection.insertOne()db.collection.replaceOne() 来代替。

语法:

db.collection.insertOne(
<document>,
   {
  writeConcern:<document>
   }
)
/*
用于向集合插入一个新文档
*/
db.teacher.insertOne(
{title:'MongoDB教程',
description:'This is a NoSQL',
by:'JunkingBoy',
tags:['mongodb','database','NoSQL']
})
db.collection.insertMany(
[<document1>,<document2>,...]
   {
  writeConcern:<document>,
  ordered:<boolean>
   }
)
db.teacher.insertMany([
{title:'MongoDB教程',
description:'This is a NoSQL',
by:'JunkingBoy',
tags:['mongodb','database','NoSQL']},
{title:'MongoDB教程',
description:'This is a NoSQL',
by:'LuciferOfLive',
tags:['mongodb','database','NoSQL']}])
/*
将数据定义为一个变量
利用变量插入
*/
document=(
{title:'MongoDB教程',
by:'Lucifer',
tags:['mongodb','database','NoSQL'],
likes:100}
)
db.teacher.insertOne(document)

插入文档你也可以使用 db.collection.save(document) 命令。如果不指定 _id 字段 save() 方法类似于 insert() 方法。如果指定 _id 字段,则会更新该 _id 的数据。

参数说明:

  • document:要写入的文档。

  • writeConcern:写入策略,默认为 1,即要求确认写操作,0 是不要求。

  • ordered:指定是否按顺序写入,默认 true,按顺序写入。--->进程写入还是方法写入

Java连接MongoDB插入文档

因为MongoDB以文档的形式存储数据。文档的数据结构和 JSON 基本一样。对应到Java中则是用List列表的方式进行添加

package mongodbtest;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

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

/**
* 使用MongoDB连接到服务器环境上
* @since JDK 1.8
* @date 0221/6/29
* @author Lucifer
*/
public class mongoconnection {

   /*配置属性*/
   private static final String MONGO_HOST = "localhost";
//   private static final Integer MONGO_PORT = 27037;
   private static final Integer MONGO_PORT = 27017;
//   private static final String MONGO_USER = "admin";
//   private static final String MONGO_PASSWORD = "r123456";
   private static final String MONGO_DB_NAME = "practice";
   private static final String GATHER_NAME = "teacher";
   private static final String GATHER_NAME2 = "demo";

   public static void getConnection(){
       /*用事务连接到远程的MongoDB服务器上*/
       try {
           /*使用java包下的类构造一个连接对象*/
           ServerAddress serverAddress = new ServerAddress(MONGO_HOST, MONGO_PORT);

           /*集群连接方法--->构造列表*/
           List<ServerAddress> addresses = new ArrayList<ServerAddress>();
           addresses.add(serverAddress);

//           /*使用Mongo包下的类MongoCredential建立连接对象*/
//           //三个参数:用户名、数据库名称、密码
//           MongoCredential credential = MongoCredential.createScramSha1Credential(MONGO_USER,
//                   MONGO_DB_NAME,
//                   MONGO_PASSWORD.toCharArray()); //最后一个形参需要转换成字符类型而不是字符串类型,使用toCharArray方法
//           /*集群连接方法--->构造列表*/
//           List<MongoCredential> credentials = new ArrayList<MongoCredential>();
//           credentials.add(credential);

           /*通过连接认证MongoDB连接--->使用MongoDBClient类下的方法*/
           MongoClient mongoClient = new MongoClient(addresses); //放入列表对象

           System.out.println("Connect to database successfully!");

           /*连接到数据库*/
           MongoDatabase mongoDatabase = mongoClient.getDatabase(MONGO_DB_NAME);

//           mongoDatabase.createCollection(GATHER_NAME2);
//           System.out.println("create gather successfully!");

           /*通过MongoCollection接口获取到集合*/
           MongoCollection<Document> collection = mongoDatabase.getCollection(GATHER_NAME);
           System.out.println("获取集合成功");

           //插入文档
           /*
           1、创建文档--->org.bson.Document(对应到MongoDB的文档数据类型).参数为key-value格式
           2、创建文档集合(List集合)
           3、将文档集合插入数据库集合中--->集合插入集合 mongoCollection.insertMany(List<Document>)
           插入单个文档可以用 mongoCollection.insertOne(Document)
            */

           /*创建文档*/
           Document document = new Document("title","Java").
                   append("description","This is a Java content").
                   append("by","JunBoy").
                   append("like",200); //在这里就是key-value的形式

           /*创建文档集合*/
           List<Document> documents = new ArrayList<>();
           /*向文档集合当中添加文档*/
           documents.add(document);

           /*将文档集合插入MongoDB数据库*/
           //使用collection类下的方法
           collection.insertMany(documents);

           System.out.println("文档插入成功!");
      }catch (Exception e){
           System.err.println(e.getClass().getName() + ":" + e.getMessage());
      }
  }
   /*
   步骤概括:
   1、利用ServerAddress类访问到地址和端口
   2、使用MongoDB的jar包下封装好的证书类(Credential)验证身份信息--->构造器:用户名、数据库名称、密码
   3、使用Mongo客户端类封装好的方法验证是否连接成功--->构造器:Address类的列表、Credential类的列表
   4、use指定的数据库--->使用mongoDatabase类下的方法连接到数据库
    */

   public static void main(String[] args) {
       getConnection();
  }
}

MongoDB更新文档

MongoDB 使用 update() 和 save() 方法来更新集合中的文档

  • update()方法,用于更新已存在的文档。

  • save()方法,通过传入的文档来替换已有文档,_id 主键存在就更新,不存在就插入。

语法:

db.collection.update(
  <query>,
  <update>,
  {
    upsert: <boolean>,
    multi: <boolean>,
    writeConcern: <document>
        /*注意这部分参数放在一个{}内*/
  }
)
//以上语句只会修改第一条发现的文档,如果你要修改多条相同的文档,则需要设置 multi 参数为 true。
db.collection.update({'title':'MongoDB 教程'},{$set:{'title':'MongoDB'}},{multi:true})
db.teacher.update(
{title:'Java'},
{$set:{title:'java'}},
{multi:true,
upsert:true})
db.teacher.update({title:'Java'},
                {title:'java'})
//这样修改原先已经存在的域的内容如果未设置会被置空
db.teacher.update(
{title:'Java'},
{$set:{title:'java'}})
//先将要修改的域赋值给一个变量然后再用变量去修改就可以保证未设置的修改的域保持原来的值

参数说明:

  • query : update的查询条件,类似sql update查询内where后面的。

  • update : update的对象和一些更新的操作符(如$,$inc...)等,也可以理解为sql update查询内set后面的

  • upsert : 可选,这个参数的意思是,如果不存在update的记录,是否插入objNew,true为插入,默认是false,不插入。

  • multi : 可选,mongodb 默认是false,只更新找到的第一条记录,如果这个参数为true,就把按条件查出来多条记录全部更新。

  • writeConcern :可选,抛出异常的级别。

db.collection.save(
  <document>,
  {
    writeConcern: <document>
  }
)

参数说明:

  • document : 文档数据。

  • writeConcern :可选,抛出异常的级别。

更多实例

只更新第一条记录:

db.col.update( { "count" : { $gt : 1 } } , { $set : { "test2" : "OK"} } );

全部更新:

db.col.update( { "count" : { $gt : 3 } } , { $set : { "test2" : "OK"} },false,true );

只添加第一条:

db.col.update( { "count" : { $gt : 4 } } , { $set : { "test5" : "OK"} },true,false );

全部添加进去:

db.col.update( { "count" : { $gt : 5 } } , { $set : { "test5" : "OK"} },true,true );

全部更新:

db.col.update( { "count" : { $gt : 15 } } , { $inc : { "count" : 1} },false,true );

只更新第一条记录:

db.col.update( { "count" : { $gt : 10 } } , { $inc : { "count" : 1} },false,false );

It's a lonely road!!!
原文地址:https://www.cnblogs.com/JunkingBoy/p/14953228.html