MongoDB更新操作(Shell)

0、数据准备

for(var i=0;i<10000;i++){
var patid="pat"+i;
var patname="name"+i;
var sex="M";
var age=parseInt(100*Math.random(i));
db.patient.insert({"patid":patid,"patname":patname,"sex":sex,"age":age,address:{"city":"shanghai","street":"huaihai road"}});
}

1、默认为全局更新

db.patient.find({"patid":"pat100"})
db.patient.update({"patid":"pat100"},{"patid":"pat100","sex":"F"})
db.patient.find({"patid":"pat100"})

2、局部更新$set

db.patient.find({"patid":"pat101"})
db.patient.update({"patid":"pat101"},{$set:{"sex":"F"}})
db.patient.find({"patid":"pat101"})

3、局部更新$inc

db.patient.find({"patid":"pat102"})
db.patient.update({"patid":"pat102"},{$inc:{"age":-100}})
db.patient.find({"patid":"pat102"})

4、批量更新

db.patient.find({"age":10})
db.patient.update({"age":10},{$set:{"age":11}})
db.patient.find({"age":10})
db.patient.update({"age":10},{$set:{"age":11}},false,true)
db.patient.find({"age":10})

5、更新时,没有匹配则插入

db.patient.find({"patid":"pidx001"})
db.patient.update({"patid":"pidx001"},{"patid":"pidx001","sex":"F"},true)
db.patient.find({"patid":"pidx001"})

MongoDB实现条件查询(Shell)

0、数据准备

for(var i=0;i<10000;i++){
var patid="pat"+i;
var patname="name"+i;
var sex="M";
var age=parseInt(100*Math.random(i));
db.patient.insert({"patid":patid,"patname":patname,"sex":sex,"age":age,address:{"city":"shanghai","street":"huaihai road"}});
}

1、比较运算符

运算符 操作符
> $gt
>= $gte
< $lt
<= $lte
!= $ne
= $eq 或 空
db.patient.find({"age":20})
db.patient.find({"age":{$eq:20}})
db.patient.find({"age":{$ne:20}})
db.patient.find({"age":{$gt:20}})
db.patient.find({"age":{$gte:20}})
db.patient.find({"age":{$lt:20}})
db.patient.find({"age":{$lte:20}})

2、逻辑运算符

运算符 操作符
And $and
Or $or
db.patient.find({$and:[{"age":10},{"age":11}]})
db.patient.find({$or:[{"age":10},{"age":11}]})

3、IN 与 Not IN

运算符 操作符
In $in
not in nin
db.patient.find({"age":{$in:[10,11]}})
db.patient.find({"age":{$nin:[10,11]}})

4、where

db.patient.find({$where:function(){return this.patid=='pat1000'}})
db.patient.find({$where:function(){return this.patid=='pat1000' || this.age==1}})

5、正则表达式

#patid以0做结尾
db.patient.find({"patid":/0$/})
#patid以pat开头
db.patient.find({"patid":{$regex:"^pat"}})
#patid以pat开头,切不区分pat大小写
db.patient.find({"patid":{$regex:"^pat",$options:"$i"}})
#patid以pat1做开头,age为10
db.patient.find({"patid":/^pat1/,age:10})

6、分页与排序

db.patient.find({"patid":/0$/}).count()
db.patient.find({"patid":/0$/}).limit(10)
db.patient.find({"patid":/0$/}).skip(10).limit(10)
db.patient.find({"patid":/0$/}).sort({"age":1})
db.patient.find({"patid":/0$/}).sort({"age":-1})

7、between是由min max来实现的

#需要age字段的索引哦
db.patient.find({"patid":/0$/}).min({"age":10}).max({"age":20})

8、全文检索

#建立text索引后,mongo会帮你分词,一个collection只能建立一个text索引
#在patname字段建立全文索引
db.patient.ensureIndex({"address.street":"text"})
#在全部字段建立全文索引
db.patient.ensureIndex({"$**": "text"})
#进行简单查询
db.patient.find({$text:{$search:"huaihai"}})

MongoDB实现分片存储(Shell)

MongoDB分片存储结构如下图所示:
Mongo分片存储

#启动配置服务
mongod --dbpath=D:\Database\MongoDB3\slice\config --port 27018
#启动mongos
mongos --port 27017 --configdb=localhost:27018
#启动mongo分片服务
mongod --dbpath=D:\Database\MongoDB3\slice\slice1 --port 27019
mongod --dbpath=D:\Database\MongoDB3\slice\slice2 --port 27020
mongo localhost:27017
#增加节点
sh.addShard("localhost:27019")
sh.addShard("localhost:27020")
#开启分片
sh.enableSharding("test")
#配置collection
sh.shardCollection("test.patient",{"patid":1},true)
#查看状态
sh.status()
#批量插入数据
#单独连一个mongo查一下试试:)
for(var i=0;i<10000;i++){
var patid="pat"+i;
var patname="name"+i;
var sex="M";
var age=parseInt(100*Math.random(i));
db.patient.insert({"patid":patid,"patname":patname,"sex":sex,"age":age,address:{"city":"shanghai","street":"huaihai road"}});
}

MongoDB索引(Shell)

for(var i=0;i<100000;i++){
var patid="pat"+i;
var patname="name"+i;
var sex="M";
var age=parseInt(100*Math.random(i));
db.patient.insert({"patid":patid,"patname":patname,"sex":sex,"age":age});
}

#普通索引
db.patient.ensureIndex({"age":1})
#唯一索引
db.patient.ensureIndex({"patid":1},{"unique":true})
#复合索引
db.patient.ensureIndex({"patname":1,"age":1})

#解释执行计划
db.patient.find({"patid":"pat1000"}).explain();
db.patient.find({"age":99}).explain();
#指定索引进行查询
db.patient.find({"age":99}).hint({"patname":1,"age":1}).explain();

#枚举索引
db.patient.getIndexes();

#删除索引
db.patient.dropIndex("age_1");

MongoDB副本集(Shell)

0、原理
副本集原理

1、开启副本集节点

mongod --dbpath=D:\Database\MongoDB3\dbc0 --port=27017 --replSet neohope
mongod --dbpath=D:\Database\MongoDB3\dbc1 --port=27018 --replSet neohope
mongod --dbpath=D:\Database\MongoDB3\dbc2 --port=27019 --replSet neohope

2、初始化副本集

mongo --port 27017
config_rs={_id:'neohope',members:[{_id:0,host:'localhost:27017'},{_id:1,host:'localhost:27018'},{_id:2,host:'localhost:27019'}]}
rs.initiate(config_rs)
rs.status()

3、增加仲裁服务器

mongod --dbpath D:\Database\MongoDB3\dbc3 --port 27020 --replSet neohope/localhost:27017,localhost:27018,localhost:27019

4、设置仲裁服务器

mongo --port 27017
neohope:PRIMARY> rs.addArb("localhost:27020");
neohope:PRIMARY> rs.status()

5、将备用节点设为被动模式

neohope:PRIMARY> r=rs.conf()
neohope:PRIMARY> r.members[2].priority=0
neohope:PRIMARY> rs.reconfig(r)
neohope:PRIMARY> rs.status()

MongoDB主从数据库(Shell)

1、主数据库

mongod --dbpath=D:\Database\MongoDB3\dbm --port=27017 --master

2、从数据库

mongod --dbpath=D:\Database\MongoDB3\dbs1\ --port=27018 --slave --source=localhost:27017

3、后期指定主数据库

mongod --dbpath=D:\Database\MongoDB3\dbs2\ --port=27019 --slave 

mongo localhost:27019
use local
db.sources.insert({"host":"localhost:27017"})
db.sources.find()

条码分类

1、一维条码
一维条码是由一组规则排列的条、空以及对应的字符组成的标记,“条”指对光线反射率较低的部分,“空”指对光线反射率较高的部分,这些条和空组成的数据表达一定的信息,并能够用特定的设备识读,转换成与计算机兼容的二进制和十进制信息。根据不同使用环境,会有不同码制,即不同条码条和空的排列规则,常用的一维码的码制包括:EAN码、39码、交叉25码、UPC码、128码、93码,ISBN码,及Codabar(库德巴码)。

常用一维条码

2、堆叠式/行排式/称堆积式/层排式二维条码
其编码原理是建立在一维条码基础之上,按需要堆积成二行或多行。它在编码设计、校验原理、识读方式等方面继承了一维条码的一些特点,识读设备与条码印刷与一维条码技术兼容。但由于行数的增加,需要对行进行判定,其译码算法与软件也不完全相同于一维条码。有代表性的行排式二维条码有:Code 16K、Code 49、PDF417、MicroPDF417 等。

3、矩阵式/棋盘式二维条码
其编码原理是在一个矩形空间通过黑、白像素在矩阵中的不同分布进行编码。在矩阵相应元素位置上,用点(方点、圆点或其他形状)的出现表示二进制“1”,点的不出现表示二进制的“0”,点的排列组合确定了矩阵式二维条码所代表的意义。矩阵式二维条码是建立在计算机图像处理技术、组合编码原理等基础上的一种新型图形符号自动识读处理码制。具有代表性的矩阵式二维条码有:Code One、MaxiCode、QR Code、 Data Matrix、Han Xin Code、Grid Matrix 等。

常用二维条码

参考:
维-基-百-科(转图片了,方便大家看)

MongoDB注册为服务(命令行)

1、安装为服务

mongod --dbpath=D:\Database\MongoDB3\db --logpath=D:\Database\MongoDB3\log\mongo.log --port 27027 --noauth --install -serviceName MongoDB01 --serviceDisplayName MongoDB01

net start MongoDB01

mongo 127.0.0.1:27027/test

2、安装为服务,并开启用户认证

mongo 127.0.0.1:27027/admin

db.createUser({"user":"neo","pwd":"neo","customData":{"hobby":"tuzi"},"roles":["readWrite", "dbAdmin"]})

net stop MongoDB01

mongod --dbpath=D:\Database\MongoDB3\db --logpath=D:\Database\MongoDB3\log\mongo.log --port 27027 --auth --reinstall -serviceName MongoDB01S --serviceDisplayName MongoDB01S

net start MongoDB01S

mongo 127.0.0.1:27027/test -u neo -p neo

MongoDB查询使用Codec的简单示例(java)

1、数据准备

db.person.insert({"name":"neo","age":"26","sex":"male"})
db.person.insert({"name":"joe","age":"28","sex":"male"})

2、使用Codec

class Person  
{
       public ObjectId _id;
       public double Age;  
       public String Name;  
       public String Sex;  
       
       public Person(ObjectId _id, String Name, double Age, String Sex)
       {
    	   this._id=_id;
    	   this.Name=Name;
    	   this.Age=Age;
    	   this.Sex=Sex;
       }
}

class PersonCodec implements Codec<Person> 
{
    private final CodecRegistry codecRegistry;

    public PersonCodec(final CodecRegistry codecRegistry) {
        this.codecRegistry = codecRegistry;
    }
    
    @Override
    public void encode(BsonWriter writer, Person t, EncoderContext ec) {
    	 writer.writeStartDocument();
         writer.writeName("_id");
         writer.writeObjectId(t._id);
         writer.writeName("name");
         writer.writeString(t.Name);
         writer.writeName("age");
         writer.writeDouble(t.Age);
         writer.writeName("sex");
         writer.writeString(t.Sex);
         writer.writeEndDocument();
    }

    @Override
    public Class<Person> getEncoderClass() {
        return Person.class;
    }

    @Override
    public Person decode(BsonReader reader, DecoderContext dc) 
    {
        reader.readStartDocument();
        reader.readName();
        ObjectId _id = reader.readObjectId();
        reader.readName();
        String name = reader.readString();
        reader.readName();
        double age = reader.readDouble();
        reader.readName();
        String sex =reader.readString();
        reader.readEndDocument();
        return new Person(_id,name,age,sex);
    }
}

class PersonCodecProvider implements CodecProvider 
{
    @Override
    public <T> Codec<T> get(Class<T> type, CodecRegistry cr) 
    {
        if (type == Person.class) 
        {
            return (Codec<T>) new PersonCodec(cr);
        }
        return null;
    }
}

public class CodecTest 
{
	private static void testCodec()
	{
		String[] hosts = {"127.0.0.1"};
		int port = 27017;
		String user = null;
		String password = null;
		String database = "test";
		CodecRegistry codecRegistry = CodecRegistries.fromRegistries(
	            CodecRegistries.fromProviders(new PersonCodecProvider()),
	            MongoClient.getDefaultCodecRegistry());  
		
		MongoClient mongoClient = getConnection(hosts,port,user,password,database,codecRegistry);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection<Person> collection = db.getCollection("person",Person.class);
		FindIterable<Person> iterable = collection.find();
		MongoCursor<Person> cursor = iterable.iterator();
		while (cursor.hasNext())
		{
        		Person p  = cursor.next();
        		System.out.println("personName: " + p.Name);
		}
	}
	
	private static MongoClient getConnection(String[] hosts, int port, String user, String password, String database, CodecRegistry codecRegistry)
	{
	        MongoClientOptions mongoClientOptions = new MongoClientOptions.Builder()
	        .connectionsPerHost(100)
	        .threadsAllowedToBlockForConnectionMultiplier(5)
	        .maxWaitTime(1000 * 60 * 2)
	        .connectTimeout(1000 * 10)
	        .socketTimeout(0)
	        .socketKeepAlive(false)
	        .readPreference(ReadPreference.primary())
	        .writeConcern(WriteConcern.ACKNOWLEDGED)
	        .codecRegistry(codecRegistry)
	        .build();
		
		List<ServerAddress> mongoAddresses = new ArrayList<ServerAddress>();
		for (String host : hosts) {
		    mongoAddresses.add(new ServerAddress(host, port));
		}
		
		List<MongoCredential> mongoCredentials = null;
		if (user != null && !user.isEmpty() && password != null && !password.isEmpty()) {
		    mongoCredentials = new ArrayList<MongoCredential>();
		    mongoCredentials.add(MongoCredential.createMongoCRCredential(user, database, password.toCharArray()));
		}
		
		if(mongoCredentials==null)
		{
			return new MongoClient(mongoAddresses, mongoClientOptions);
		}
		else
		{
			return new MongoClient(mongoAddresses, mongoCredentials, mongoClientOptions);
		}
	}
}

MongoDB的MapReduce简单示例(java)

1、数据准备

db.sell.insert({"price":8.0,"amount":500.0,"status":"a"})
db.sell.insert({"price":8.0,"amount":450.0,"status":"a"})
db.sell.insert({"price":8.0,"amount":400.0,"status":"a"})
db.sell.insert({"price":9.0,"amount":350.0,"status":"a"})
db.sell.insert({"price":9.0,"amount":300.0,"status":"a"})
db.sell.insert({"price":9.0,"amount":250.0,"status":"a"})
db.sell.insert({"price":9.0,"amount":200.0,"status":"a"})
db.sell.insert({"price":10.0,"amount":150.0,"status":"d"})
db.sell.insert({"price":10.0,"amount":100.0,"status":"d"})
db.sell.insert({"price":10.0,"amount":50.0,"status":"d"})
db.sell.insert({"price":10.0,"amount":0.0,"status":"d"})

2、MapReduce

	private static void testMapReduce3x()
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		MongoCollection collection = db.getCollection("sell");

		String map = "function(){emit(this.price,this.amount);}";
		String reduce = "function(key, values){return Array.sum(values)}";

		MapReduceIterable out = collection.mapReduce(map, reduce);
		MongoCursor cursor = out.iterator();
		while (cursor.hasNext()) 
		{
			System.out.println(cursor.next());
		}
	}
	
	private static void testMapReduce2x()
	{
		MongoClient mongoClient = new MongoClient("localhost", 27017);
		MongoDatabase db = mongoClient.getDatabase("test");
		BasicDBObject query=new BasicDBObject("status","a");
		DBCollection dbcollection = mongoClient.getDB("test").getCollection("sell");
		
		String map = "function(){emit(this.price,this.amount);}";
		String reduce = "function(key, values){return Array.sum(values)}";
		
		MapReduceCommand cmd = new MapReduceCommand(dbcollection, map, reduce,
		    "outputCollection", MapReduceCommand.OutputType.INLINE, query);
		
		MapReduceOutput out2 = dbcollection.mapReduce(cmd);
		for (DBObject o : out2.results()) 
		{
		   System.out.println(o.toString());
		}
	}