https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/

db.coll_test.getIndexes()##查看index
db.coll_test.totalIndexSize()##查看index大小
db.coll_test.count() ##查看数据条数
db.coll_test.dataSize(); ##查看数据大小
db.coll_test.getDB() ##获取集合的数据库名
db.coll_test.stats() ##集合的状态
db.coll_test.getShardVersion();

1 db.collection.aggregate() 聚合
use test
--db.tutorialspoint.insert
var res = db.coll_test.insertMany([
{ _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 },
{ _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 },
{ _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 },
{ _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 },
{ _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }])

MyMongo:PRIMARY> var res = db.coll_test.insertMany([
... { _id: 1, cust_id: "abc1", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 },
... { _id: 2, cust_id: "xyz1", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 },
... { _id: 3, cust_id: "xyz1", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 },
... { _id: 4, cust_id: "xyz1", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 },
... { _id: 5, cust_id: "abc1", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }])
MyMongo:PRIMARY> res
{ "acknowledged" : true, "insertedIds" : [ 1, 2, 3, 4, 5 ] }
MyMongo:PRIMARY> db.coll_test.find()
{ "_id" : 1, "cust_id" : "abc1", "ord_date" : ISODate("2012-11-02T17:04:11.102Z"), "status" : "A", "amount" : 50 }
{ "_id" : 2, "cust_id" : "xyz1", "ord_date" : ISODate("2013-10-01T17:04:11.102Z"), "status" : "A", "amount" : 100 }
{ "_id" : 3, "cust_id" : "xyz1", "ord_date" : ISODate("2013-10-12T17:04:11.102Z"), "status" : "D", "amount" : 25 }
{ "_id" : 4, "cust_id" : "xyz1", "ord_date" : ISODate("2013-10-11T17:04:11.102Z"), "status" : "D", "amount" : 125 }
{ "_id" : 5, "cust_id" : "abc1", "ord_date" : ISODate("2013-11-12T17:04:11.102Z"), "status" : "A", "amount" : 25 }
##Group by and Calculate a Sum
db.coll_test.aggregate([
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
])
##The operation returns a cursor with the following documents:
{ "_id" : "xyz1", "total" : 100 }
{ "_id" : "abc1", "total" : 75 }
##Return Information on Aggregation Pipeline Operation
db.coll_test.aggregate(
[
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
],
{
explain: true
}
)
##Perform Large Sort Operation with External Sort¶
var results = db.coll_test.aggregate(
[
{ $project : { cusip: 1, date: 1, price: 1, _id: 0 } },
{ $sort : { cusip : 1, date: 1 } }
],
{
allowDiskUse: true
}
)
##Specify an Initial Batch Size
db.coll_test.aggregate(
[
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 2 }
],
{
cursor: { batchSize: 0 }
}
)
A batchSize of 0 means an empty first batch and is useful for quickly returning a cursor or failure message
without doing significant server-side work. Specify subsequent batch sizes to OP_GET_MORE operations as with other MongoDB cursors
#Collation
var res = db.myColl.insertMany([
{ _id: 1, category: "café", status: "A" },
{ _id: 2, category: "cafe", status: "a" },
{ _id: 3, category: "cafE", status: "a" }])
MyMongo:PRIMARY> db.myColl.find()
{ "_id" : 1, "category" : "café", "status" : "A" }
{ "_id" : 2, "category" : "cafe", "status" : "a" }
{ "_id" : 3, "category" : "cafE", "status" : "a" }
db.myColl.aggregate(
[ { $match: { status: "A" } }, { $group: { _id: "$category", count: { $sum: 1 } } } ],
{ collation: { locale: "fr", strength: 1 } }
);
##Hint an Index
db.foodColl.insert([
{ _id: 1, category: "cake", type: "chocolate", qty: 10 },
{ _id: 2, category: "cake", type: "ice cream", qty: 25 },
{ _id: 3, category: "pie", type: "boston cream", qty: 20 },
{ _id: 4, category: "pie", type: "blueberry", qty: 15 }
])
db.foodColl.createIndex( { qty: 1, type: 1 } );
db.foodColl.createIndex( { qty: 1, category: 1 } );
db.foodColl.aggregate(
[ { $sort: { qty: 1 }}, { $match: { category: "cake", qty: 10 } }, { $sort: { type: -1 } } ],
{ hint: { qty: 1, category: 1 } }
)
返回{ "_id" : 1, "category" : "cake", "type" : "chocolate", "qty" : 10 }
#Override readConcern
The following operation on a replica set specifies a Read Concern of "majority" to read the most recent copy of the data
confirmed as having been written to a majority of the nodes.
To use read concern level of "majority", replica sets must use WiredTiger storage engine and election protocol version 1.
To ensure that a single thread can read its own writes, use "majority" read concern and "majority" write concern against the primary of the replica set.
To use a read concern level of "majority", you cannot include the $out stage.
Regardless of the read concern level, the most recent data on a node may not reflect the most recent version of the data in the system.

2 db.collection.bulkWrite()
insertOne
updateOne
updateMany
deleteOne
deleteMany
replaceOne
db.collection.bulkWrite( [
{ insertOne : { "document" : <document> } }
] )
db.collection.bulkWrite( [
{ updateOne :
{
"filter" : <document>,
"update" : <document>,
"upsert" : <boolean>,
"collation": <document>,
"arrayFilters": [ <filterdocument1>, ... ]
}
}
] )
db.collection.bulkWrite( [
{ updateMany :
{
"filter" : <document>,
"update" : <document>,
"upsert" : <boolean>,
"collation": <document>,
"arrayFilters": [ <filterdocument1>, ... ]
}
}
] )

3 db.collection.copyTo()
db.collection.copyTo(newCollection)
Copies all documents from collection into newCollection using server-side JavaScript. If newCollection does not exist, MongoDB creates it.
If authorization is enabled, you must have access to all actions on all resources in order to run db.collection.copyTo().

4 db.collection.count()
db.myColl.aggregate(
[
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
db.collection.aggregate(
[
{ $match: <query condition> },
{ $group: { _id: null, count: { $sum: 1 } } }
]
)
#Index Use
{ a: 1, b: 1 },the following operations can return the count using only the index
db.collection.find( { a: 5, b: 5 } ).count()
db.collection.find( { a: { $gt: 5 } } ).count()
db.collection.find( { a: 5, b: { $gt: 10 } } ).count()
---MongoDB must also read the documents to return the count.
db.collection.find( { a: 5, b: { $in: [ 1, 2, 3 ] } } ).count()
db.collection.find( { a: { $gt: 5 }, b: 5 } ).count()
db.collection.find( { a: 5, b: 5, c: 5 } ).count()
In such cases, during the initial read of the documents, MongoDB pages the documents into memory such that subsequent calls of the same count operation will have better performance
#Count all Documents in a Collection
MyMongo:PRIMARY> db.myColl.count()//db.myColl.find().count()
3
Count all Documents that Match a Query
db.orders.count( { ord_dt: { $gt: new Date('01/01/2012') } } )
db.orders.find( { ord_dt: { $gt: new Date('01/01/2012') } } ).count()

4 db.collection.createIndex()
db.collection.createIndex(keys, options)
MongoDB supports several different index types including text, geospatial, and hashed indexes
Starting in 3.6, you cannot specify * as the index name.
db.myColl.createIndex( { category: 1 }, { collation: { locale: "fr" } } )
db.myColl.find( { category: "cafe" } ).collation( { locale: "fr" } )
db.myColl.find( { category: "cafe" } ) //which by default uses the “simple” binary collator, cannot use the index:
For a compound index where the index prefix keys are not strings, arrays, and embedded documents, an operation that specifies a different
collation can still use the index to support comparisons on the index prefix keys.
db.myColl.createIndex(
{ score: 1, price: 1, category: 1 },
{ collation: { locale: "fr" } } )
db.myColl.find( { score: 5 } ).sort( { price: 1 } )//can use the index
db.myColl.find( { score: 5, price: { $gt: NumberDecimal( "10" ) } } ).sort( { price: 1 } ) //can use the index
db.myColl.find( { score: 5, category: "cafe" } )
#Options for text Indexes
#Options for 2dsphere Indexes
#Options for 2d Indexes
#Options for geoHaystack Indexes
db.collection.createIndex( { orderDate: 1 } )
db.collection.createIndex( { orderDate: 1, zipcode: -1 } )
db.collection.createIndex(
{ category: 1 },
{ name: "category_fr", collation: { locale: "fr", strength: 2 } }
)
db.collection.createIndex(
{ orderDate: 1, category: 1 },
{ name: "date_category_fr", collation: { locale: "fr", strength: 2 } }
)

5 db.collection.createIndexes()
To create a text, a 2d, or a geoHaystack index on a collection that has a non-simple collation, you must explicitly specify
{collation: {locale: "simple"} } when creating the index.

6 db.collection.dataSize()
MyMongo:PRIMARY> db.myColl.dataSize()
154
MyMongo:PRIMARY> db.myColl.stats()

7 db.collection.deleteOne()//只删除一行
try {
db.orders.deleteOne( { "_id" : ObjectId("563237a41a4d68582c2509da") } );
} catch (e) {
print(e);
}
try {
db.orders.deleteOne(
{ "_id" : ObjectId("563237a41a4d68582c2509da") },
{ w : "majority", wtimeout : 100 }
);
} catch (e) {
print (e);
}
db.myColl.deleteOne(
{ category: "cafe", status: "A" },
{ collation: { locale: "fr", strength: 1 } }
)
db.collection.deleteMany()//删除满足条件的多行
MyMongo:PRIMARY> db.myColl.deleteMany( { status: "a" }, { collation: { locale: "fr", strength: 1 } } )
{ "acknowledged" : true, "deletedCount" : 3 }

8 db.collection.distinct()
var res = db.inventory.insertMany([
{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] },
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] },
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" },
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }])
MyMongo:PRIMARY> db.inventory.distinct( "dept" )
[ "A", "B" ]
MyMongo:PRIMARY> db.inventory.distinct( "item.sku" )//Return Distinct Values for an Embedded Field
[ "111", "222", "333" ]
MyMongo:PRIMARY> db.inventory.distinct( "sizes" )//Return Distinct Values for an Array Field,The method returns the following array of distinct sizes values
[ "M", "S", "L" ]
MyMongo:PRIMARY> db.inventory.distinct( "item.sku", { dept: "A" } )//Specify Query with distinct
[ "111", "333" ]

MyMongo:PRIMARY> db.myColl.distinct( "category", {}, { collation: { locale: "fr", strength: 1 } } )
[ "café" ]

9 db.collection.drop()
The following operation drops the students collection in the current database.
db.students.drop()

10 db.collection.dropIndex()
db.pets.dropIndex( "catIdx" )
db.pets.dropIndex( { "cat" : -1 } )

11 db.collection.ensureIndex()
Use db.collection.createIndex() rather than db.collection.ensureIndex() to create new indexes.

12 db.collection.explain()
db.collection.explain().<method(...)>
db.products.explain().remove( { category: "apparel" }, { justOne: true } )
db.collection.explain().find()
MyMongo:PRIMARY> db.myColl.explain().find( { category: "cafe" } ).collation( { locale: "fr" } )
db.products.explain().count( { quantity: { $gt: 50 } } )
db.products.explain("executionStats").find(
{ quantity: { $gt: 50 }, category: "apparel" }
)

mongodb collection method的更多相关文章

  1. How to duplicate the records in a MongoDB collection

      // Fill out a literal array of collections you want to duplicate the records in. // Iterate over e ...

  2. Scala Collection Method

    接收一元函数 map 转换元素,主要应用于不可变集合 (1 to 10).map(i => i * i) (1 to 10).flatMap(i => (1 to i).map(j =&g ...

  3. MongoDB collection Index DB 大小查询

    1.collection中的数据大小 db.collection.dataSize() 2.为collection分配的空间大小,包括未使用的空间db.collection.storageSize() ...

  4. MongoDB学习(管理数据库和集合)

    管理数据库 显示数据库列表 show dbs 切换到其他数据库 use <database_name> 创建数据库 MongoDB没有提供显式的创建数据库的MongoDB shell命令. ...

  5. Recovering a WiredTiger collection from a corrupt MongoDB installation

    Reference: http://www.alexbevi.com/blog/2016/02/10/recovering-a-wiredtiger-collection-from-a-corrupt ...

  6. MongoDB - basic

    mongoDB basic from:http://www.tutorialspoint.com/mongodb prject:https://github.com/chenxing12/l4mong ...

  7. node连接--MongoDB

    简介: 传统关系类型(ORM:Object-Relational Mapper),MongoDB(ODM:Object Document Mapper); MongoDB是一个面向文档,schme无关 ...

  8. Codeigniter MongoDB类库

    安装方法:1.将mongodb.php 放到config目录2.将Mongo_db.php放到library目录 使用方法: $this->mongo_db->where_gte('age ...

  9. MongoDB - The mongo Shell, Access the mongo Shell Help

    In addition to the documentation in the MongoDB Manual, the mongo shell provides some additional inf ...

随机推荐

  1. hql join

    文章一: 1.用hql语句 ` String hql="select student.id, student.name ,class.name from student映射实体类名 as s ...

  2. UVA 11731 Ex-circles (外切圆)

    题意:给你三角形的三条边,求图中DEF的面积和阴影部分的面积. 题解:一些模板,三角形的旁切圆半径:.与 三旁心为 #include<set> #include<map> #i ...

  3. linux系统内SAMBA共享问题

    最近将项目迁移到了公司服务器上,以后客户端调试和服务端开发都要去链接这台服务器,但是开发就需要调试,也需要log信息,同一局域网内,如何链接服务器并随时查看服务器上的log信息呢? 今天搞了一下,把步 ...

  4. 一款简易的CSS3扁平化风格联系表单

    CSS3扁平化风格联系表单是一款CSS3简易联系表单非常清新,整体外观不是那么华丽,但是表单扁平化的风格让人看了非常舒服,同时利用了HTML5元素的特性,表单的验证功能变得也相当简单.经测试效果相当不 ...

  5. unity监测按下键的键值并输出+unity键值

    using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using U ...

  6. 解决 Amoeba连接mysql出错 解决方案

    今天配置mysql的主从复制 用到了Amoeba.从安装到启动服务,我深深地体会到学运维的不易. 首先是  安装错误  的解决,连接错误  的兄弟可以直接往下拉. 安装错误 1.出现 JAVA_HOM ...

  7. chromedriver驱动的浏览器和真实浏览器之间的差异

    一. 打印百度首页底部的声明 如图,想打印@2018 Baidu...后面的一长串文字,可以通过class name定位的形式 可以看出,只有一个class name是"copyright- ...

  8. Ceph的现状

    转自:https://www.ustack.com/blog/ceph-distributed-block-storage/ 1. Ceph简介 Ceph是统一分布式存储系统,具有优异的性能.可靠性. ...

  9. mysql 授予远程连接直接访问

    不通过ssh通道,mysql 授予远程连接直接访问 语句 GRANT ALL PRIVILEGES ON *.* TO root@'%' IDENTIFIED BY '!DSJdg!' WITH GR ...

  10. js对象数组 根据某个共同字段 分组

    var arr = [ {"id":"1001","name":"值1","value":" ...