Mongodb basis

MongoDB Quick Start: 
1 Download mongodb package and unzip to your target folder;
2 run "mongod --dbpath folderName" to start a mongodb instance; the -- dbpath specify the data folder path;3 run mongo to connect to the default local mongodb instance;
4 useful commands: 
show dbs
show collections
use dbname
db.collectionName.find({criteria}, {projections}).limit(size).sort({modifier}).batchSize(size);
Note: the batchSize() doesn‘t change the output size(20) in the mongo shell;


How to exclude fields:

db.user.find({}, {‘fieldName1‘:0, ‘fieldName2‘: 0})
db.user.find({}, {‘_id‘:0})//exclude the id column;

$gt/$gte/$lt/$lte: the value of the column should great than/great than or equal/less than/less than or equal to the value specified;
db.people.find({score: {$gt: 80}}) will return people whose score great than 80;

$exists: return the documents that contains/don‘t contains the column specified;
db.people.find({hobbies: {$exists: true}});

$nin: return the documents that the filed value is on in the specified array, or the filed doesn‘t exist;
db.user.find({age: {$nin: [12, 24, 36, 48, 60, 72, 84, 96, 108]}})//选择非本命年的user

$ne: return the documents that the field value not equals the the value specified, or the field doesn‘t exist;

$type: column data type should match the type specified;
db.people.find({‘a‘: {$type: 1}}); will return the people whose attribute a should be double type;
The type list:
Double=1 String=2 Object=3 Array=4 (Binary data)=5
(Object id)=7 Boolean=8 Date=9 Null=10 (Regular expression)=11
(JavaScript code)=13 Symbol=14 (JavaScript code with scope)=15 (32-bit integer)=16 Timestamp=17 (64-bit integer)=18

$or: like ‘or‘ operation in SQL, return the documents match at least one criteria specified;
db.people.find({$or:[{score: 80},{score:90}]}) will return the people whose score is 80 or 90;

$and: like ‘and‘ operation in SQL, return the documents math all the criteria specified;
db.people.find({$and:[{score: {$gt:80}},{score:{$lt: 90}}]}) will return people whose score great than 80 but less than 90;

$all: The array column should contain all the elements specified;
db.people.find({favorites:{$all : [‘bear‘,‘cheese‘]}})  will return the people whose favorites should contain beer and cheese;

$in: the column should match at least one of the values specified;
db.people.find({name: {$in:[‘a‘,‘b‘]}}): will return people whose name is a or b;

query inside array: for array columns, if any value in the array match the criteria, then the document will be selected;
db.people.find({favorites: ‘beer‘}) will return any people who like to drink beer; // the favorites column is array;

query on nested documents: 如果需要匹配一个内嵌的文档,则内嵌文档必需完全匹配,比如你有:
{name: ‘xs06974‘,email: {work: ‘[email protected]‘, personal: ‘[email protected]‘}}
则下面的查询会返回记录:db.people.find({email: {work: ‘[email protected]‘, personal: ‘[email protected]‘}})但是下面的查询不会返回:db.people.find({email: {personal: ‘[email protected]‘,work: ‘[email protected]‘}}),尽管查询的email实质上应该是一致的;因为mongodb是按字节比较bson;
这个查询是可以的: db.people.find({‘email.work‘:‘[email protected]‘}); ‘email.work‘两边的引号是必需的;

Manipulate cursor:
var cur = db.people.find();
cur.hasNext(); will return if it contains any documents;cur.next() will return the next document;
cur.skip(n): will skip n documents;
cur.sort({colomnName: -1/1});
cur.limit(n) will only return n documents;
cursor的sort, limit, skip在server端被执行 一旦被执行,就不能再次调用;

count():
db.people.count(); count all the people;
db.people.count({score: {$gt: 80}}); count people whose score great than 80;

distinct():
db.user.distinct(‘age‘);

update():
db.collection.update({criteria}, {new document}); 该update方法将使用新的文档完全替代旧的文档;是比较危险的;
db.people.update({name: ‘john‘}, {name: ‘john1‘})

upsert:
db.people.update({name:‘xx06974‘},{$set:{age:30}}, {upsert: true}) update the documents if exist, otherwise, insert a new one;

$set: 
change partial of the document;
db.people.update({‘name‘:‘john‘}, {$set: {age: 30}})

$unset: 
remove some properties of a document;
db.people.update({‘name‘:‘john‘}, {$unset: {height: 1}})

Manipulate array:
$push: 
db.people.update({name:‘john‘, {$push: {favorites: ‘bear‘}}});
$pushAll: db.people.update({name: ‘john‘}, {$pushAll:{a: [‘cheese‘,‘cocacola‘]}});
$pull:db.people.update({name: ‘john‘}, {$pull:{a: ‘cheese‘}});//remove from the array;$pullAll: db.people.update({name: ‘john‘}, {$pullAll:{a: [‘cheese‘,‘cocacola‘]}});// remove multiple from array;
$addToSet: db.people.update({name: ‘john‘}, {$pullAll:{a:‘cheese}});// add if not exists;

update multiple documents:db.people.update({}, {age: 12}, {multi: true}); will update all the documents matched; otherwise, will only update one document;
Please remember: Mongodb doesn‘t provide isolated transaction mechanism: there is a single thread to update the data, and it updates some documents for a operation A, then it will yield and let other operations to be executed; then it will pick up operation A again;
The mongodb can guarantee for a single document update;
User program can construct isolate mechanism in their program by intruducing lock;

remove();
db.people.remove({criteria}): remove matched documents one by one;
db.people.drop(); like truncate in SQL, remove the collections; the operation is in one transaction;

How to choose between refreences and embedded object(s) or How to choose between normalization and denormalization?
1 If two models will always be retrieved at the same time, it is better to use embedded object. 
For example: the one-to-one relationship in User -> Contact; Otherwise, you should consider using reference;
2 If the embedded-object model leads to huge repetition, you should consider using reference:
For example: in the Book-Publisher relationship, some books may share the same publisher, so pub a embedded Publisher object under Book is not a good idea;

What should be considered in One-to-Many reference model?
We should consider in witch part should we store the reference; For example, in the Company-Employee relationship, if we store the reference into the company, the references size may grow as well as the company size grow;

时间: 2024-10-22 00:11:12

Mongodb basis的相关文章

走进MongoDB(二)

本文从以下四个方面对mongodb进行介绍 一.聚合操作(aggregate operation) 二.文本搜索(text search) 三.数据模型 (DATA MODELS) 四.数据库安全(security) 一.聚合操作 组合多个数据记录,对分组数据记录进行多种操作,最终返回一个单一的结果 实现方式:聚合管道.map-reduce.单用途聚合方法 1.聚合管道 聚合管道是基于数据处理管道模型上的.数据记录经过 多个阶段的管道 最终被转换为聚合结果集. 最基本的过滤管道提供了改变数据集输

MySQL vs. MongoDB: Choosing a Data Management Solution

原文地址:http://www.javacodegeeks.com/2015/07/mysql-vs-mongodb.html 1. Introduction It would be fair to say that as IT professionals we are living in the golden age of data management era. As our software systems become more complex and more distributed,

DB Intro - MongoDB Basic

mongoDB basic from:http://www.tutorialspoint.com/mongodb prject:https://github.com/chenxing12/l4mongodb overview getting-start collection dataType insert find Overview MongoDB is a cross-platform, document oriented database that provides, high perfor

mongodb基础-索引

1.索引介绍 mongodb的索引和我们遇到的rdbms的索引含义一样,原理也基本一样 首先我们先在一个没有索引的集合上做一个查询,具体的查询计划可以通过explain()函数获取: > db.t1.find({"username":"user101"}).explain() { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "

MongoDB十二种最有效的模式设计【转】

持续关注MongoDB博客(https://www.mongodb.com/blog)的同学一定会留意到,技术大牛Daniel Coupal 和 Ken W. Alger ,从 今年 2月17 号开始,在博客上持续发表了 如何在MongoDB中设计数据库模式的方法.截止到今日(4月20号),12种模式设计的方法已全部与读者见面.本人认为,此系列文章,总结的非常全面,很多地方有首创性,涵盖的场景也很多,并且有理论总结,也有案例分析.文中分享的很多知识使人"如听仙乐耳暂明",开卷受益,常读

MongoDB 3.2变动一览

3.2测试版本总算release了!E叔带大家来一览MongoDB 3.2版本的真容. (PS:内容比较多,在此仅针对个人认为比较重要的进行讲解,markdown写的,貌似WP的markdown插件有点奇怪,格式出来和写的时候不太一样,有点丑,大家见谅.) 以下是原文链接: Development Release Notes for 3.2.0 Release Candidate storage engine change WiredTiger引擎将是默认引擎了. dbpath中有数据,在配置中

ubuntu安装mongodb

参考:http://blog.csdn.net/zhushh/article/details/52451441 1.导入软件源的公钥 sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927 2.为mongodb创建软件源list文件 ubuntu12.04 echo "deb http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.2 multi

mongodb 安装、windows服务、创建用户

http://www.cnblogs.com/best/p/6212807.html 打开MongoDB的安装目录如“C:\Program Files\MongoDB\Server\3.4\bin”,并在此目录下新建一个mongo.config文件,文件内容如下: ##数据库目录## dbpath=C:\data\db ##日志输出文件## logpath=C:\data\log\db.log 使用cmd进入命令行 使用cd切换目录到安装目录下,如:cd  C:\Program Files\Mo

MongoDB 学习笔记之 WriteConcern

WriteConcern: 转载:MongoDB WriteConcern(写关注)机制 http://www.ywnds.com/?p=3688&viewuser=40 MongoDB部署模式 MongoDB的部署模式有三种:第一种是单机模式(开发测试):第二种是高可用复制集:第三种是可扩展分片集群.如下图所示. 知道了MongoDB几种常用的部署模式之后,接下来我们看看每种部署模式的写操作过程. MongoDB单点写操作 从上图可以看出,其中primary是MongoDB的一个实例,里面有两