Mongodb 批量操作命令

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。

MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

一、MongoDB常见类型

MongoDB常见类型 说明 Object ID 文档ID String 字符串,最常用,必须是有效的UTF-8 Boolean 存储一个布尔值,true或false Integer 整数可以是32位或64位,这取决于服务器 Double 存储浮点值 Arrays 数组(js)或列表(python),多个值存储到一个键 Object 用于嵌入式的文档,即一个值为一个文档 Null 存储Null值 Timestamp 时间戳 Date 存储当前日期或时间的UNIX时间格式

二、数据库操作

1、显示数据库列表

show dbs

2、切换或创建数据(有则切换,无则创建)

use 数据库名

3、删除数据库

db.dropDatabase()

三、集合操作

1、创建集合

db.createCollection(集合名, [参数])

2、查看集合

show collections/show tables

3、删除集合

db.集合名.drop()

四、数据基础操作

1、新增 db.集合名.insert({“键名1”:值1, “键名2”: 值2 …}) db.yunfan_test.insert({“name”:“张三”,“age”:24}) 2、查询 db.集合名.findOne() # 查询一行 db.集合名.find() # 查询全部 db.集合名.find().pretty() # 格式化打印db.集合名.find({查找条件}) # 按条件查找 db.yunfan_test.find({“age”:24}) 3、修改 db.集合名.update({查询条件}, {修改后结果}) #修改整行 db.students.update({查找条件}, {KaTeX parse error: Expected 'EOF', got '}' at position 41: …修改的字段名2": "值2"}}̲) #修改指定字段的值 d…set:{“age”:26}}) 4、删除 db.集合名.remove({查询条件}) db.集合名.remove({}) # 删除全部数据 db.yunfan_test.remove({“name”:“张三”}) db.yunfan_test.remove({})

五、高级查询

1、比较运算符查询 db.集合名.find({“键名”: {比较运算符1:值1, 比较运算符2:值2} }) db.yunfan_test.find({“age”: {$lt:24}}) 说明:

符号 释义 $gt 大于 $lt 小于 $gte 大于等于 $lte 小于等于欧 KaTeX parse error: Expected '}', got 'EOF' at end of input: …名.find({"键名": {in:[值1, 值2, 值3 …]} }) db.集合名.find({“键名”: {KaTeX parse error: Expected 'EOF', got '}' at position 21: …值1, 值2, 值3 ...]}̲ })db.yunfan_te…in:[20,21,22]}}) db.yunfan_test.find({“age”:{KaTeX parse error: Expected 'EOF', got '}' at position 14: in:[20,21,22]}̲}) 3、size db.集合…size:n} }) db.yunfan_test.find({“list”:{KaTeX parse error: Expected 'EOF', got '}' at position 7: size:3}̲}) 4、exists db.…exist: true|false} }) db.yunfan_test.find({“flag”:{KaTeX parse error: Expected 'EOF', got '}' at position 12: exists:true}̲}) 5、or db.集合名.…or:[{条件1}, {条件2}, {条件3}…]}) db.yunfan_test.find({$or:[{“name”:“张三”},{“name”:“李四”}]}) 6、模糊查询 db.集合名.find({“键名”: js正则表达) db.yunfan_test.find({“name”:/张三/}) 7、查询结果排序(sort) db.集合名.find().sort({“键名”: 1|-1, “键名”: 1|-1…}) #1为升序, -1为降序 db.yunfan_test.find().sort({“age”:-1}) 8、限定返回结果数量(limit) db.集合名.find().limit(n) db.集合名.find().skip(n) # 跳过n条,返回从n+1k开始的数据 db.集合名.find().skip(n).limit(m) # 跳过n条,返回后面的m条 db.yunfan_test.find().limit(1).sort({“age”:1}) 9、查询返回结果数量(count) db.集合名.find().count() db.集合名.find().skip(n).count(true) # 与skip结合使用时,要加true db.yunfan_test.find().count() 10、聚合函数 分组函数 说明

s

u

m

计算总和,

sum 计算总和,

sum计算总和,sum:1同count表示计数 $avg 计算平均值 $min 获取最小值 $max 获取最大值 $push 在结果文档中插入值到一个数组中,相当于拼接字段 $first 根据资源文档的排序获取第一个文档数据 KaTeX parse error: Expected '}', got 'EOF' at end of input: …集合名.aggregate({group:{_id:‘KaTeX parse error: Expected '}', got 'EOF' at end of input: 字段名', 别名:{聚合函数:’$字段名’}}} ); 例:

统计同年龄的人数 db.yunfan_test.aggregate({KaTeX parse error: Expected '}', got 'EOF' at end of input: group:{_id:'age’,count_age:{KaTeX parse error: Expected 'EOF', got '}' at position 6: sum:1}̲}} );# 统计所有人平均年…group:{_id:null,总人数:{KaTeX parse error: Expected 'EOF', got '}' at position 6: sum:1}̲,avg_age:{avg:“KaTeX parse error: Expected 'EOF', got '}' at position 5: age"}̲,min_age:{min:“KaTeX parse error: Expected 'EOF', got '}' at position 5: age"}̲,max_age:{max:”$age”}}} );

六、批量删除:

Examples

Delete Multiple Documents The orders collection has documents with the following structure: { _id: ObjectId(“563237a41a4d68582c2509da”), stock: “Brent Crude Futures”, qty: 250, type: “buy-limit”, limit: 48.90, creationts: ISODate(“2015-11-01T12:30:15Z”), expiryts: ISODate(“2015-11-01T12:35:15Z”), client: “Crude Traders Inc.” }

The following operation deletes all documents where client : “Crude Traders Inc.”: try { db.orders.deleteMany( { “client” : “Crude Traders Inc.” } ); } catch (e) { print (e); }

The operation returns: { “acknowledged” : true, “deletedCount” : 10 }

The following operation deletes all documents where stock : “Brent Crude Futures” and limitis greater than 48.88: try { db.orders.deleteMany( { “stock” : “Brent Crude Futures”, “limit” : { $gt : 48.88 } } ); } catch (e) { print (e); }

The operation returns: { “acknowledged” : true, “deletedCount” : 8 }

deleteMany() with Write Concern Given a three member replica set, the following operation specifies a w of majority and wtimeout of 100: try { db.orders.deleteMany( { “client” : “Crude Traders Inc.” }, { w : “majority”, wtimeout : 100 } ); } catch (e) { print (e); }

If the acknowledgement takes longer than the wtimeout limit, the following exception is thrown: WriteConcernError({ “code” : 64, “errInfo” : { “wtimeout” : true }, “errmsg” : “waiting for replication timed out” })

七、批量添加、批量更新

Write Operations insertOne Inserts a single document into the collection. See db.collection.insertOne(). db.collection.bulkWrite( [ { insertOne : { “document” : } } ] )

updateOne and updateMany updateOne updates a single document in the collection that matches the filter. If multiple documents match,updateOne will update the first matching document only. See db.collection.updateOne(). db.collection.bulkWrite( [ { updateOne : { “filter” : , “update” : , “upsert” : } } ] )

updateMany updates all documents in the collection that match the filter. Seedb.collection.updateMany(). db.collection.bulkWrite( [ { updateMany : { “filter” : , “update” : , “upsert” : } } ] )

Use query selectors such as those used with find() for the filter field. Use Update Operators such as $set, $unset, or $rename for the update field. By default, upsert is false. replaceOne replaceOne replaces a single document in the collection that matches the filter. If multiple documents match, replaceOne will replace the first matching document only. Seedb.collection.replaceOne(). db.collection.bulkWrite([ { replaceOne : { “filter” : , “replacement” : , “upsert” : } } ] )

Use query selectors such as those used with find() for the filter field. The replacement field cannot contain update operators. By default, upsert is false. deleteOne and deleteMany deleteOne deletes a single document in the collection that match the filter. If multiple documents match,deleteOne will delete the first matching document only. See db.collection.deleteOne(). db.collection.bulkWrite([ { deleteOne : { “filter” : } } ] )

deleteMany deletes all documents in the collection that match the filter. Seedb.collection.deleteMany(). db.collection.bulkWrite([ { deleteMany : { “filter” : } } ] )

Use query selectors such as those used with find() for the filter field. _id Field If the document does not specify an _id field, then mongod adds the _id field and assign a uniqueObjectId for the document before inserting or upserting it. Most drivers create an ObjectId and insert the_id field, but the mongod will create and populate the _id if the driver or application does not. If the document contains an _id field, the _id value must be unique within the collection to avoid duplicate key error. Update or replace operations cannot specify an _id value that differs from the original document.

八. 操作命令 Execution of Operations

The ordered parameter specifies whether bulkWrite() will execute operations in order or not. By default, operations are executed in order. The following code represents a bulkWrite() with five operations. db.collection.bulkWrite( [ { insertOne : }, { updateOne : }, { updateMany : }, { replaceOne : }, { deleteOne : }, { deleteMany : } ] )

In the default ordered : true state, each operation will be executed in order, from the first operationinsertOne to the last operation deleteMany. If ordered is set to false, operations may be reordered by mongod to increase performance. Applications should not depend on order of operation execution. The following code represents an unordered bulkWrite() with six operations: db.collection.bulkWrite( [ { insertOne : }, { updateOne : }, { updateMany : }, { replaceOne : }, { deleteOne : }, { deleteMany : } ], { ordered : false } )

With ordered : false, the results of the operation may vary. For example, the deleteOne ordeleteMany may remove more or fewer documents depending on whether the run before or after theinsertOne, updateOne, updateMany, or replaceOne operations. Each group of operations can have at most 1000 operations. If a group exceeds this limit, MongoDB will divide the group into smaller groups of 1000 or less. For example, if the queue consists of 2000 operations, MongoDB creates 2 groups, each with 1000 operations. The sizes and grouping mechanics are internal performance details and are subject to change in future versions. Executing an ordered list of operations on a sharded collection will generally be slower than executing anunordered list since with an ordered list, each operation must wait for the previous operation to finish. Capped Collections bulkWrite() write operations have restrictions when used on a capped collection. updateOne and updateMany throw a WriteError if the update criteria increases the size of the document being modified. replaceOne throws a WriteError if the replacement document has a larger size than the original document. deleteOne and deleteMany throw a WriteError if used on a capped collection. Error Handling bulkWrite() throws a BulkWriteError exception on errors. Excluding Write Concern errors, ordered operations stop after an error, while unordered operations continue to process any remaining write operations in the queue. Write concern errors are displayed in the writeConcernErrors field, while all other errors are displayed in the writeErrors field. If an error is encountered, the number of successful write operations are displayed instead of the inserted _id values. Ordered operations display the single error encountered while unordered operations display each error in an array. Examples Bulk Write Operations The characters collection contains the following documents: { “_id” : 1, “char” : “Brisbane”, “class” : “monk”, “lvl” : 4 }, { “_id” : 2, “char” : “Eldon”, “class” : “alchemist”, “lvl” : 3 }, { “_id” : 3, “char” : “Meldane”, “class” : “ranger”, “lvl” : 3 }

The following bulkWrite() performs multiple operations on the collection: 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); }

The operation returns the following: { “acknowledged” : true, “deletedCount” : 1, “insertedCount” : 2, “matchedCount” : 2, “upsertedCount” : 0, “insertedIds” : { “0” : 4, “1” : 5 }, “upsertedIds” : {

} }

If the _id value for the second of the insertOne operations were a duplicate of an existing _id, the following exception would be thrown: BulkWriteError({ “writeErrors” : [ { “index” : 0, “code” : 11000, “errmsg” : “E11000 duplicate key error collection: guidebook.characters index: id dup key: { : 4 }”, “op” : { “_id” : 5, “char” : “Taeln” } } ], “writeConcernErrors” : [ ], “nInserted” : 1, “nUpserted” : 0, “nMatched” : 0, “nModified” : 0, “nRemoved” : 0, “upserted” : [ ] })

Since ordered was true by default, only the first operation completes successfully. The rest are not executed. Running the bulkWrite() with ordered : false would allow the remaining operations to complete despite the error. Unordered Bulk Write The characters collection contains the following documents: { “_id” : 1, “char” : “Brisbane”, “class” : “monk”, “lvl” : 4 }, { “_id” : 2, “char” : “Eldon”, “class” : “alchemist”, “lvl” : 3 }, { “_id” : 3, “char” : “Meldane”, “class” : “ranger”, “lvl” : 3 }

The following bulkWrite() performs multiple unordered operations on the characters collection. Note that one of the insertOne stages has a duplicate _id value: try { db.characters.bulkWrite( [ { insertOne : { “document” : { “_id” : 4, “char” : “Dithras”, “class” : “barbarian”, “lvl” : 4 } } }, { insertOne : { “document” : { “_id” : 4, “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 } } } ], { ordered : false } ); } catch (e) { print(e); }

The operation returns the following: BulkWriteError({ “writeErrors” : [ { “index” : 0, “code” : 11000, “errmsg” : “E11000 duplicate key error collection: guidebook.characters index: id dup key: { : 4 }”, “op” : { “_id” : 4, “char” : “Taeln” } } ], “writeConcernErrors” : [ ], “nInserted” : 1, “nUpserted” : 0, “nMatched” : 2, “nModified” : 2, “nRemoved” : 1, “upserted” : [ ] })

Since this was an unordered operation, the writes remaining in the queue were processed despite the exception. Bulk Write with Write Concern The enemies collection contains the following documents: { “_id” : 1, “char” : “goblin”, “rating” : 1, “encounter” : 0.24 }, { “_id” : 2, “char” : “hobgoblin”, “rating” : 1.5, “encounter” : 0.30 }, { “_id” : 3, “char” : “ogre”, “rating” : 3, “encounter” : 0.2 }, { “_id” : 4, “char” : “ogre berserker” , “rating” : 3.5, “encounter” : 0.12}

The following bulkWrite() performs multiple operations on the collection using a write concern value of"majority" and timeout value of 100 milliseconds: try { db.enemies.bulkWrite( [ { updateMany : { “filter” : { “rating” : { $gte : 3} }, “update” : { $inc : { “encounter” : 0.1 } } },

},

{ updateMany :

{

"filter" : { "rating" : { $lt : 2} },

"update" : { $inc : { "encounter" : -0.25 } }

},

},

{ deleteMany : { "filter" : { "encounter" { $lt : 0 } } } },

{ insertOne :

{

"document" :

{

"_id" :5, "char" : "ogrekin" , "rating" : 2, "encounter" : 0.31

}

}

}

],

{ writeConcern : { w : "majority", wtimeout : 100 } }

); } catch (e) { print(e); }

If the total time required for all required nodes in the replica set to acknowledge the write operation is greater than wtimeout, the following writeConcernError is displayed when the wtimeout period has passed. BulkWriteError({ “writeErrors” : [ ], “writeConcernErrors” : [ { “code” : 64, “errInfo” : { “wtimeout” : true }, “errmsg” : “waiting for replication timed out” } ], “nInserted” : 1, “nUpserted” : 0, “nMatched” : 4, “nModified” : 4, “nRemoved” : 1, “upserted” : [ ] })

精彩内容

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。