驱动和客户端库

https://mongodb-documentation.readthedocs.org/en/latest/ecosystem/drivers.html#id2

https://mongodb-documentation.readthedocs.org/en/latest/ecosystem/drivers/cpp-to-sql-to-mongo-shell.html

窗体顶端

 
 

窗体底端

SQL to mongo Shell to C++

MongoDB queries are expressed as JSON (BSON) objects. This quick reference chart shows examples as SQL, mongo shell syntax, and MongoDB C++ driver syntax.

A query expression in MongoDB (and other things, such as an index key pattern) is represented as BSON. In C++ you can use BSONObjBuilder (aka bson::bob) to build BSON objects, or the BSON() macro. The examples below assume a connection c already established:

using namespace bson;

DBClientConnection c;

c.connect("somehost");

Several of the C++ driver methods throw mongo::DBException, so you will want a try/catch statement as some level in your program. Also be sure to call c.getLastError() after writes to check the error code.

SQL

mongo Shell

C++ Driver

INSERT INTO USERS

VALUES( 1, 1)

db.users.insert( { a: 1, b: 1 } )

// GENOID is optional. if not done by client,

// server will add an _id

c.insert("mydb.users",

BSON(GENOID<<"a"<<1<<"b"<<1));

// then:

string err = c.getLastError();

SELECT a,b FROM users

db.users.find( {},

{a: 1, b: 1 }

)

auto_ptr<DBClientCursor> cursor =

c.query("mydb.users", Query(),

0, 0, BSON("a"<<1<<"b"<<1));

SELECT * FROM users

db.users.find()

auto_ptr<DBClientCursor> cursor =

c.query("mydb.users", Query());

SELECT *

FROM users

WHERE age=33

db.users.find( { age: 33 } )

auto_ptr<DBClientCursor> cursor =

c.query("mydb.users", QUERY("age"<<33))

// or:

auto_ptr<DBClientCursor> cursor =

c.query("mydb.users", BSON("age"<<33))

SELECT *

FROM users

WHERE age=33

ORDER BY name

db.users.find( { age: 33 } ).sort( { name: 1 } )

auto_ptr<DBClientCursor> cursor =

c.query("mydb.users",

QUERY("age"<<33).sort("name"));

SELECT *

FROM users

WHERE age>33

AND age<=40

db.users.find( { 'age': { $gt:33, $lte:40 } } )

auto_ptr<DBClientCursor> cursor =

c.query("mydb.users",

QUERY("age"<<GT<<33<<LTE<<40));

CREATE INDEX myindexname

ON users(name)

db.users.ensureIndex( {name: 1 } )

c.ensureIndex("mydb.users", BSON("name"<<1));

SELECT *

FROM users

LIMIT 10

SKIP 20

db.users.find().limit(10).skip(20)

auto_ptr<DBClientCursor> cursor =

c.query("mydb.users", Query(),

10, 20);

SELECT * FROM users LIMIT 1

db.users.findOne()

bo obj = c.findOne("mydb.users", Query());

SELECT DISTINCT last_name

FROM users

WHERE x=1

db.users.distinct( 'last_name', {x: 1} )

// no helper for distinct yet in c++ driver,

// so send command manually

bo cmdResult;

bool ok = c.runCommand(

"mydb",

BSON("distinct" << "users"

<< "key" << "last_name"

<< "query" << BSON("x"<<1)),

cmdResult);

list<bo> results;

cmdResult["values"].Obj().Vals(results);

SELECT COUNT(*)

FROM users

where AGE > 30

db.users.find( { age: { $gt: 30 } } ).count()

unsigned long long n =

c.count("mydb.users", BSON("age"<<GT<<30));

UPDATE users

SET a=a+2

WHERE b='q'

db.users.update( { b: 'q' },

{ $inc: { a:2 } },

false, true)

c.update("mydb.users", QUERY("b"<<"q"),

BSON("$inc"<<BSON("a"<<2)), false, true);

// then optionally:

string err = c.getLastError();

bool ok = err.empty();

DELETE

FROM users

WHERE z="abc"

db.users.remove( { z: 'abc' } )

c.remove("mydb.users", QUERY("z"<<"abc"));

// then optionally:

string err = c.getLastError();

也可以参考

SQL to MongoDB Mapping Chart

In addition to the charts that follow, you might want to consider the Frequently Asked Questions section for a selection of common questions about MongoDB.

Terminology and Concepts

The following table presents the various SQL terminology and concepts and the corresponding MongoDB terminology and concepts.

SQL Terms/Concepts

MongoDB Terms/Concepts

database

database

table

collection

row

document or BSON document

column

field

index

index

table joins

embedded documents and linking

primary key

Specify any unique column or column combination as primary key.

primary key

In MongoDB, the primary key is automatically set to the _idfield.

aggregation (e.g. group by)

aggregation pipeline

See the SQL to Aggregation Mapping Chart.

Executables

The following table presents the MySQL/Oracle executables and the corresponding MongoDB executables.

 

MySQL/Oracle

MongoDB

Database Server

mysqld/oracle

mongod

Database Client

mysql/sqlplus

mongo

Examples

The following table presents the various SQL statements and the corresponding MongoDB statements. The examples in the table assume the following conditions:

  • The SQL examples assume a table named users.
  • The MongoDB examples assume a collection named users that contain documents of the following prototype:
·                {
·                  _id: ObjectID("509a8fb2f3f4948bd2f983a0"),
·                  user_id: "abc123",
·                  age: 55,
·                  status: 'A'
·                }

Create and Alter

The following table presents the various SQL statements related to table-level actions and the corresponding MongoDB statements.

SQL Schema Statements

MongoDB Schema Statements

Reference

CREATE TABLE users (
    id MEDIUMINT NOT NULL
        AUTO_INCREMENT,
    user_id Varchar(30),
    age Number,
    status char(1),
    PRIMARY KEY (id)
)

Implicitly created on first insert() operation. The primary key_id is automatically added if _id field is not specified.

db.users.insert( {
    user_id: "abc123",
    age: 55,
    status: "A"
 } )

However, you can also explicitly create a collection:

db.createCollection("users")

See insert() anddb.createCollection()for more information.

ALTER TABLE users
ADD join_date DATETIME

Collections do not describe or enforce the structure of its documents; i.e. there is no structural alteration at the collection level.

However, at the document level, update() operations can add fields to existing documents using the $set operator.

db.users.update(
    { },
    { $set: { join_date: new Date() } },
    { multi: true }
)

See the Data Modeling Conceptsupdate(), and$set for more information on changing the structure of documents in a collection.

ALTER TABLE users
DROP COLUMN join_date

Collections do not describe or enforce the structure of its documents; i.e. there is no structural alteration at the collection level.

However, at the document level, update() operations can remove fields from documents using the $unset operator.

db.users.update(
    { },
    { $unset: { join_date: "" } },
    { multi: true }
)

See Data Modeling Conceptsupdate(), and$unset for more information on changing the structure of documents in a collection.

CREATE INDEX idx_user_id_asc
ON users(user_id)
db.users.ensureIndex( { user_id: 1 } )

See ensureIndex() andindexes for more information.

CREATE INDEX
       idx_user_id_asc_age_desc
ON users(user_id, age DESC)
db.users.ensureIndex( { user_id: 1, age: -1 } )

See ensureIndex() andindexes for more information.

DROP TABLE users
db.users.drop()

See drop() for more information.

Insert

The following table presents the various SQL statements related to inserting records into tables and the corresponding MongoDB statements.

SQL INSERT Statements

MongoDB insert() Statements

Reference

INSERT INTO users(user_id,
                  age,
                  status)
VALUES ("bcd001",
        45,
        "A")
db.users.insert( {
       user_id: "bcd001",
       age: 45,
       status: "A"
} )

See insert() for more information.

Select

The following table presents the various SQL statements related to reading records from tables and the corresponding MongoDB statements.

SQL SELECT Statements

MongoDB find() Statements

Reference

SELECT *
FROM users
db.users.find()

See find()for more information.

SELECT id, user_id, status
FROM users
db.users.find(
    { },
    { user_id: 1, status: 1 }
)

See find()for more information.

SELECT user_id, status
FROM users
db.users.find(
    { },
    { user_id: 1, status: 1, _id: 0 }
)

See find()for more information.

SELECT *
FROM users
WHERE status = "A"
db.users.find(
    { status: "A" }
)

See find()for more information.

SELECT user_id, status
FROM users
WHERE status = "A"
db.users.find(
    { status: "A" },
    { user_id: 1, status: 1, _id: 0 }
)

See find()for more information.

SELECT *
FROM users
WHERE status != "A"
db.users.find(
    { status: { $ne: "A" } }
)

See find()and $ne for more information.

SELECT *
FROM users
WHERE status = "A"
AND age = 50
db.users.find(
    { status: "A",
      age: 50 }
)

See find()and $andfor more information.

SELECT *
FROM users
WHERE status = "A"
OR age = 50
db.users.find(
    { $or: [ { status: "A" } ,
             { age: 50 } ] }
)

See find()and $or for more information.

SELECT *
FROM users
WHERE age > 25
db.users.find(
    { age: { $gt: 25 } }
)

See find()and $gt for more information.

SELECT *
FROM users
WHERE age < 25
db.users.find(
   { age: { $lt: 25 } }
)

See find()and $lt for more information.

SELECT *
FROM users
WHERE age > 25
AND   age <= 50
db.users.find(
   { age: { $gt: 25, $lte: 50 } }
)

Seefind(),$gt, and$lte for more information.

SELECT *
FROM users
WHERE user_id like "%bc%"
db.users.find(
   { user_id: /bc/ }
)

See find()and $regexfor more information.

SELECT *
FROM users
WHERE user_id like "bc%"
db.users.find(
   { user_id: /^bc/ }
)

See find()and $regexfor more information.

SELECT *
FROM users
WHERE status = "A"
ORDER BY user_id ASC
db.users.find( { status: "A" } ).sort( { user_id: 1 } )

See find()and sort()for more information.

SELECT *
FROM users
WHERE status = "A"
ORDER BY user_id DESC
db.users.find( { status: "A" } ).sort( { user_id: -1 } )

See find()and sort()for more information.

SELECT COUNT(*)
FROM users
db.users.count()

or

db.users.find().count()

See find()andcount() for more information.

SELECT COUNT(user_id)
FROM users
db.users.count( { user_id: { $exists: true } } )

or

db.users.find( { user_id: { $exists: true } } ).count()

Seefind(),count(), and$exists for more information.

SELECT COUNT(*)
FROM users
WHERE age > 30
db.users.count( { age: { $gt: 30 } } )

or

db.users.find( { age: { $gt: 30 } } ).count()

Seefind(),count(), and $gt for more information.

SELECT DISTINCT(status)
FROM users
db.users.distinct( "status" )

See find()anddistinct()for more information.

SELECT *
FROM users
LIMIT 1
db.users.findOne()

or

db.users.find().limit(1)

Seefind(),findOne(), andlimit() for more information.

SELECT *
FROM users
LIMIT 5
SKIP 10
db.users.find().limit(5).skip(10)

Seefind(),limit(), and skip()for more information.

EXPLAIN SELECT *
FROM users
WHERE status = "A"

mongodb(基础用法)的更多相关文章

  1. mongodb基础用法

    安装部分 mongodb配置方法 mongodb的安装目录 C:\MongoDB\Server\3.2\bin 创建以下目录 c:\mongo\log c:\mongo\db 创建mongodb的配置 ...

  2. Mongodb基础用法及查询操作[转载]

    插入多条测试数据> for(i=1;i<=1000;i++){... db.blog.insert({"title":i,"content":&qu ...

  3. Mongodb基础用法及查询操作

    插入多条测试数据> for(i=1;i<=1000;i++){... db.blog.insert({"title":i,"content":&qu ...

  4. MongoDB 监控 --- MongoDB基础用法(八)

    MongoDB 监控 在你已经安装部署并允许MongoDB服务后,你必须要了解MongoDB的运行情况,并查看MongoDB的性能.这样在大流量得情况下可以很好的应对并保证MongoDB正常运作. M ...

  5. MongoDB 数据备份和恢复 --- MongoDB基础用法(七)

    数据备份 在Mongodb中我们使用mongodump命令来备份MongoDB数据.该命令可以导出所有数据到指定目录中. mongodump命令可以通过参数指定导出的数据量级转存的服务器. mongo ...

  6. MongoDB分片 --- MongoDB基础用法(六)

    分片 在Mongodb里面存在另一种集群,就是分片技术,可以满足MongoDB数据量大量增长的需求. 当MongoDB存储海量的数据时,一台机器可能不足以存储数据,也可能不足以提供可接受的读写吞吐量. ...

  7. MongoDB复制 --- MongoDB基础用法(五)

    复制 MongoDB复制是将数据同步在多个服务器的过程. 复制提供了数据的冗余备份,并在多个服务器上存储数据副本,提高了数据的可用性, 并可以保证数据的安全性. 复制还允许您从硬件故障和服务中断中恢复 ...

  8. MongoDB Java连接---MongoDB基础用法(四)

    MongoDB 连接 标准 URI 连接语法: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN ...

  9. MongoDB用户,角色管理 --- MongoDB基础用法(三)

    用户管理 用户创建 MongoDB采用基于角色的访问控制(RBAC)来确定用户的访问. 授予用户一个或多个角色,确定用户对MongoDB资源的访问权限和用户可以执行哪些操作. 用户应该只有最小权限集才 ...

随机推荐

  1. Groovy Spock环境的安装

    听说spock是一个加强版的Junit,今天特地安装了,再把过程给大家分享一下. 首先说明,我的Java项目是用maven管理的. 我用的Eclipse是Kelper,开普勒. 要使用Spock之前, ...

  2. sudo权限添加 和 rpm、deb之名词解释

    sudo权限添加: 刚开始用Center_os Linux操作系统,想装个输入法,搜了一下,看到linux下的搜狗输入法(帖子链接)下载下来的文件的扩展名是.deb,直接用帖子上的一个命令: sudo ...

  3. ffmpeg常用基本命令(转)

    [FFmpeg]FFmpeg常用基本命令 1.分离视频音频流 ffmpeg -i input_file -vcodec copy -an output_file_video //分离视频流 ffmpe ...

  4. 《生活就像练习》读书笔记(一)——AQAL理论和象限

    摘自<生活就像练习>肯威尔伯 著 北京:同心出版社,2012.6 AQAL整合理论 AQAL的意思是“所有象限.所有层面.所有路线.所有状态.所有类型”.练习的真正目的是:努力阐释瞬息万变 ...

  5. Myeclipse其实和Eclipse差不多的, 至少不输出来的项目时一模一样的

    http://zhidao.baidu.com/link?url=LiaDdzRYJtarYvpL_co-Zgno31Az7QiS0VFxGm351K3gWa225oU6-NFEfkalJB3lGV6 ...

  6. activiti-explorer:使用mysql导入外部bpmn文件后存在乱码的问题

    我已经采取了如下步骤,但是仍然还是乱码 1. 在mysql中创建数据库时指定使用utf8编码: CREATE DATABASE Activiti DEFAULT CHARACTER SET utf8 ...

  7. 在View页面,使用@if(){ }输出判断正确的内容

    @if (true) { Html.Raw("已结束"); } 发现这段代码是正确,但是页面不输出"已结束"三个字,但是也不报错 @if (DateTime.N ...

  8. 熟悉linux开发环境(实验)

    北京电子科技学院(BESTI) 实验报告 课程: 深入理解计算机系统 班级: 1353班 姓名:张若嘉 杨舒雯 学号:20135330 20135324 成绩: 指导教师:娄嘉鹏 实验日期:2015. ...

  9. IOS开发之——类似微信摇一摇的功能实现

    首先,一直以为摇一摇的功能实现好高大上,结果百度了.我自己也模仿写了一个demo.主要代码如下: 新建一个项目,名字为AnimationShake. 主要代码: - (void)motionBegan ...

  10. Jenkins进阶系列之——01使用email-ext替换Jenkins的默认邮件通知

    1 简述 众所周知,Jenkins默认提供了一个邮件通知,能在构建失败.构建不稳定等状态后发送邮件.但是它本身有很多局限性,比如它的邮件通知无法提供详细的邮件内容.无法定义发送邮件的格式.无法定义灵活 ...