笔记-mongodb数据操作

1.      数据操作

1.1.    插入

db.COLLECTION_NAME.insert(document)

案例:

db.inventory.insertOne(

{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }

)

如果该集合不在该数据库中, MongoDB 会自动创建该集合并插入文档;

返回一个field,就是它在数据库中的样子。

{ "_id" : ObjectId("5cd25bc779076536c9113317"), "item" : "canvas", "qty" : 100,

"tags" : [ "cotton" ], "size" : { "h" : 28, "w" : 35.5, "uom" : "cm" } }

一次插入多条记录

db.inventory.insertMany([

{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },

{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },

{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }

])

返回结果如下:

{

"acknowledged" : true,

"insertedIds" : [

ObjectId("5cd25cbd79076536c9113318"),

ObjectId("5cd25cbd79076536c9113319"),

ObjectId("5cd25cbd79076536c911331a")

]

}

1.1.1.   insert behavior

如果集合不存在,插入操作会自动创建集合。

_id Field

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _idfield.

This also applies to documents inserted through update operations with upsert: true.

集合中的每个文档都必需有一个_id域作为主键。如果插入时没有指定,mongodb自动生成一个Objectid

Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions

对于单个document而言,所有的写操作都是原子化的。

When a single write operation (e.g. db.collection.updateMany()) modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic.

对于集合则不然。

1.2.    查询

1.2.1.    find()

MongoDB 查询文档使用 find(),它以非结构化的方式来显示所有文档。

db.collection.find(query, projection)

query :可选,使用查询操作符指定查询条件

projection :可选,使用投影操作符指定返回的键。查询时返回文档中所有键值, 只需省略该参数即可(默认省略)。

如果你需要以易读的方式来读取数据,可以使用 pretty() 方法,语法格式如下:

>db.col.find().pretty()

pretty() 方法以格式化的方式来显示所有文档。

findOne():只返回第一个满足条件的文档。

The db.collection.find() method returns a cursor to the matching documents.

它返回一个cursor

MongoDB 与 RDBMS的等效 Where 子句

要在一些条件的基础上查询文档,可以使用以下条件语句。

oper

语法

示例

等效语句

=

{<key>:<value>}

db.mycol.find({"by":"yiibai"}).pretty()

where by = 'yiibai'

<

{<key>:{$lt:<value>}}

db.mycol.find({"likes":{$lt:50}}).pretty()

where likes < 50

<=

{<key>:{$lte:<value>}}

db.mycol.find({"likes":{$lte:50}}).pretty()

where likes <= 50

>

{<key>:{$gt:<value>}}

db.mycol.find({"likes":{$gt:50}}).pretty()

where likes > 50

>=

{<key>:{$gte:<value>}}

db.mycol.find({"likes":{$gte:50}}).pretty()

where likes >= 50

!=

{<key>:{$ne:<value>}}

db.mycol.find({"likes":{$ne:50}}).pretty()

where likes != 50

db.inventory.find( {} ) # 返回所有document,等效于slect * from table;

1.2.2.    条件查询

db.inventory.find( { status: "D" } )等效于SELECT * FROM inventory WHERE status = "D"

db.inventory.find( { status: { $in: [ "A", "D" ] } } ) 等效于SELECT * FROM inventory WHERE status in ("A", "D")

db.inventory.find( { status: "A", qty: { $lt: 30 } } )等效于SELECT * FROM inventory WHERE status = "A" AND qty < 30

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )等效于SELECT * FROM inventory WHERE status = "A" OR qty < 30

db.inventory.find( {

status: "A",

$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]

} )等效于SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")

还有一些对于嵌套/队列/位/的查询操作方法,太细了,以后用到再写。

1.2.3.   projection投影

投影是指选择返回的字段。类似于select col_name1,…. from table;

在projection参数中,0代表隐藏,1代表显示。

db.inventory.find( { status: "A" }, { item: 1, status: 1 } )等效于

SELECT _id, item, status from inventory WHERE status = "A"

如果不想显示_id,需要显示声明参数:

db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )

上面都是正向选择,下面是反向排除,就是除了声明列,其它都显示:

db.inventory.find( { status: "A" }, { status: 0, instock: 0 } )

1.3.    更新

This page uses the following mongo shell methods:

db.collection.updateOne(<filter>, <update>, <options>)

db.collection.updateMany(<filter>, <update>, <options>)

db.collection.replaceOne(<filter>, <update>, <options>)

1.3.1.   updateone()

db.inventory.updateOne(

{ item: "paper" },

{

$set: { "size.uom": "cm", status: "P" },

$currentDate: { lastModified: true }

}

)

释义:

使用$set操作符更新 size.uom field to "cm" and the value of the statusfield to "P",

使用$currentDate 操作符更新 lastModified field的值;如果该域不存在,操作符会自动创建。

1.3.2.   updatemany()

db.inventory.updateMany(

{ "qty": { $lt: 50 } },

{

$set: { "size.uom": "in", status: "P" },

$currentDate: { lastModified: true }

}

)

释义:

更新所有qry小于50的文档的指定域。

1.3.3.   replaceone

将指定文档的内容整体更换掉,除了_id域。

db.inventory.replaceOne(

{ item: "paper" },

{ item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }

)

1.3.4.    behavior

Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions.

原子性,对于文档是原子化的。

_id Field

Once set, you cannot update the value of the _id field nor can you replace an existing document with a replacement document that has a different _id field value.

一旦设定,_id域是不能理发的

Document Size

For the deprecated MMAPv1, when performing update operations that increase the document size beyond the allocated space for that document, the update operation relocates the document on disk.

简单来说,如果超出指定大小,会重定位(不确定是整个文档重写然后定位还是拆分文档的域)。

Field Order

MongoDB preserves the order of the document fields following write operations except for the following cases:

The _id field is always the first field in the document.

Updates that include renaming of field names may result in the reordering of fields in the document.

Changed in version 2.6: Starting in version 2.6, MongoDB actively attempts to preserve the field order in a document. Before version 2.6, MongoDB did not actively preserve the order of the fields in a document.

Upsert Option

If updateOne()updateMany(), or replaceOne() includes upsert : true and no documents match the specified filter, then the operation creates a new document and inserts it. If there are matching documents, then the operation modifies or replaces the matching document or documents.

For details on the new document created, see the individual reference pages for the methods.

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.

1.3.5.    其它方法

db.collection.updateOne()

Updates at most a single document that match a specified filter even though multiple documents may match the specified filter.

New in version 3.2.

db.collection.updateMany()

Update all documents that match a specified filter.

New in version 3.2.

db.collection.replaceOne()

Replaces at most a single document that match a specified filter even though multiple documents may match the specified filter.

New in version 3.2.

db.collection.update()

Either updates or replaces a single document that match a specified filter or updates all documents that match a specified filter.

By default, the db.collection.update() method updates a single document. To update multiple documents, use the multi option.

Additional Methods

The following methods can also update documents from a collection:

db.collection.findOneAndReplace().

db.collection.findOneAndUpdate().

db.collection.findAndModify().

db.collection.save().

db.collection.bulkWrite().

1.4.    删除

方法:

db.collection.deleteMany()

db.collection.deleteOne()

实验:

查看当前文档内容

db.inventory.find({},{status:1})

单条删除

The following example deletes the first document where status is "D":

db.inventory.deleteOne( { status: "D" } )

多条删除

> db.inventory.deleteMany( { status: "D" } )

{ "acknowledged" : true, "deletedCount" : 5 }

结果是删除5个文档

db.inventory.deleteMany({}) #删除所有文档

1.4.1.   behavior

Indexes

Delete operations do not drop indexes, even if deleting all documents from a collection.

删除操作不会删除索引,即使删除所有文档也是如此。

Atomicity

All write operations in MongoDB are atomic on the level of a single document. For more information on MongoDB and atomicity, see Atomicity and Transactions.

Write Acknowledgement

With write concerns, you can specify the level of acknowledgement requested from MongoDB for write operations. For details, see Write Concern.

1.5.    批量写bulk write operations

try {

db.characters.bulkWrite(

[

{ insertOne :

{

"document" :

{

"_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4

}

}

},

{ insertOne :

{

"document" :

{

"_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3

}

}

},

{ updateOne :

{

"filter" : { "char" : "Eldon" },

"update" : { $set : { "status" : "Critical Injury" } }

}

},

{ deleteOne :

{ "filter" : { "char" : "Brisbane"} }

},

{ replaceOne :

{

"filter" : { "char" : "Meldane" },

"replacement" : { "char" : "Tanys", "class" : "oracle", "lvl" : 4 }

}

}

]

);

}

catch (e) {

print(e);

}

特性多了也头晕,不知道哪一种更合适,用的多了程序复杂性又高。。。。。

笔记-mongodb数据操作的更多相关文章

  1. EasyUI-datagrid数据展示+MongoDB数据操作

    使用EasyUI-datagrid进行数据展示:进行添加,修改,删除操作逻辑代码,数据源来自MongoDB. 一.新建SiteInfo控制器,添加Index页面:http://www.cnblogs. ...

  2. 6.1课堂笔记—DML(数据操作语言),DQL查询语句

    一.DML(数据操作语言) InnoDB MyISAM 支持事务 不支持事务 不支持全文索引 支持全文索引 支持外键约束 不支持 命令查看默认存储引擎 show variables like '%st ...

  3. mongodb 数据操作CRUD

    链接到mongo 新建超级用户 上文中我们提到mongo用户库表管理.为了方便我们先新建一个root权限的用户. db.createUser({user:'dbadmin',pwd:'123456', ...

  4. PHP学习笔记7-JSON数据操作

    JSON,全称是JavaScript Object Notation.它是基于JavaScript编程语言ECMA-262 3rd Edition-December 1999标准的一种轻量级的数据交换 ...

  5. mongodb数据操作(CRUD)

    1.数据插入db.集合名.insert() 操作 > use hk switched to db hk > show collections > db.info.insert({&q ...

  6. MongoDB数据操作之删除与游标处理

    删除数据(比较常用) 范例:清空infos集合中的内容.表.文档.成员. db.infos.remove({"url":/-/}); 默认情况下都删除,第二个条件设为true,只删 ...

  7. Mongodb数据操作基础

    var mongodb = require('mongodb'); var server = new mongodb.Server('localhost', 27017, {auto_reconnec ...

  8. [知了堂学习笔记]_JSON数据操作第2讲(JSON的封装与解析)

    上一讲为大家讲了什么是JSON,那么这一讲为大家带来了在WEB项目中JSON的用法,也就是JSON的封装与解析. 此图是数据库中的部分内容 一.JSON封装 所谓的JSON封装,指的是在Servlet ...

  9. [知了堂学习笔记]_JSON数据操作第1讲(初识JSON)

    一.认识JSON 什么是JSON? JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式..它基于 ECMAScript (w3c制定的js规 ...

随机推荐

  1. Codeforces Round #621 (Div. 1 + Div. 2) D

    题意: 给n,m,k,有n个点,m条线,距离都是一: 有k个特殊点,选择其中两个,进行相连,距离变为1,使得原本的最短路,经过相连改变小或者不变,最终结果是所有结果里面的最大距离. 思路: 选择i,j ...

  2. python之nosetest

    nose介绍 nose下载 nose使用 -s 能够打印用例中的print信息 ➜ func_tests git:(master) ✗ nosetests -v test_app.py:TestApp ...

  3. Go_runtime包

    package main import ( "fmt" "runtime" "time" ) //写在init函数里,main函数运行之前就 ...

  4. 洛谷 P2709 小B的询问(莫队)

    题目链接:https://www.luogu.com.cn/problem/P2709 这道题是模板莫队,然后$i$在$[l,r]$区间内的个数就是$vis[ ]$数组 $add()$和$del()$ ...

  5. Mysql2docx自动生成数据库说明文档

    [需要python3.0以上] 首先安装Mysql2docx,如下: pip install Mysql2docx 然后打开pycharm,新建test.py # python from Mysql2 ...

  6. Dubbo监控中心搭建-dubbo-monitor-simple的使用

    场景 Dubbo环境搭建-管理控制台dubbo-admin实现服务监控: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/10362 ...

  7. Postman如何测试Webservice接口?

    一般情况下使用soapui工具测试ws接口,那么能不能使用postman测试呢?当然可以,往下看. 1. 首先请求类型为post 填写上ws地址 ,url地址后不追加?wsdl 2. 设置请求头 he ...

  8. opencv python:图像梯度

    一阶导数与Soble算子 二阶导数与拉普拉斯算子 图像边缘: Soble算子: 二阶导数: 拉普拉斯算子: import cv2 as cv import numpy as np # 图像梯度(由x, ...

  9. ACM进阶之路

    第一阶段:练经典常用算法,下面的每个算法给我打上十到二十遍,同时自己精简代码, 因为太常用,所以要练到写时不用想,10-15分钟内打完,甚至关掉显示器都可以把程序打 出来. 3.大数(高精度)加减乘除 ...

  10. python+树莓派实现IoT(物联网)数据上传到服务器

    环境:raspbian-stretch(2018-06-27) 树莓派:3代B型 1.树莓派设备,需要在野外也能拥有独立联网能力,那必不可少的需要使用物联网模块. 这里使用的是微雪的SIM868通讯模 ...