mongodb collection method
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的更多相关文章
- 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 ...
- Scala Collection Method
接收一元函数 map 转换元素,主要应用于不可变集合 (1 to 10).map(i => i * i) (1 to 10).flatMap(i => (1 to i).map(j =&g ...
- MongoDB collection Index DB 大小查询
1.collection中的数据大小 db.collection.dataSize() 2.为collection分配的空间大小,包括未使用的空间db.collection.storageSize() ...
- MongoDB学习(管理数据库和集合)
管理数据库 显示数据库列表 show dbs 切换到其他数据库 use <database_name> 创建数据库 MongoDB没有提供显式的创建数据库的MongoDB shell命令. ...
- 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 ...
- MongoDB - basic
mongoDB basic from:http://www.tutorialspoint.com/mongodb prject:https://github.com/chenxing12/l4mong ...
- node连接--MongoDB
简介: 传统关系类型(ORM:Object-Relational Mapper),MongoDB(ODM:Object Document Mapper); MongoDB是一个面向文档,schme无关 ...
- Codeigniter MongoDB类库
安装方法:1.将mongodb.php 放到config目录2.将Mongo_db.php放到library目录 使用方法: $this->mongo_db->where_gte('age ...
- 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 ...
随机推荐
- [BZOJ4730][清华集训2016][UOJ266] Alice和Bob又在玩游戏
题意:俩智障又在玩游戏.规则如下: 给定n个点,m条无向边(m<=n-1),保证无环,对于每一个联通块,编号最小的为它们的根(也就是形成了一片这样的森林),每次可以选择一个点,将其本身与其祖先全 ...
- Codeforces Round #425 (Div. 2) D 树链剖分 + 树状数组维护区间
一看就知道 可以LCA判断做 也可以树链剖分拿头暴力 然而快速读入和线段树维护区间会T70 于是只能LCA? 线段树的常数不小 于是需要另外一种办法来进行区间加减和查询区间和 就是使用树状数组 这个题 ...
- SBT搭建Spark
http://www.cnblogs.com/yongjian/p/6211007.html http://www.aboutyun.com/thread-8587-1-1.html http://b ...
- Valid Parentheses有效括号匹配。利用栈。
问题描述:给定一个字符串,其中只包含字符‘{’, '}', '[', ']', '(', ')'确定如果输入字符串是有效的.括号必须以正确的顺序排列,“()”和“()[]{ ...
- UVA 11827 水
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem ...
- js备忘录模式
备忘录(Memento):在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态.这样以后就可将该对象恢复到原先保存的状态. 备忘录模式比较适用于功能比较复杂的,但需要维护或记录属性 ...
- js写出斐波那契数列
斐波那契数列:1.1.2.3.5.8.13.21.34.…… 函数: 使用公式f[n]=f[n-1]+f[n-2],依次递归计算,递归结束条件是f[1]=1,f[2]=1. for循环: 从底层向上运 ...
- Windows7 如何关闭系统更新
我们点击开始菜单,找到控制面板这个选项,如图: 然后进入操作中心,如图: 然后选择如图所示的选项,如图: 然后选择更改设置选项,如图: 然后我们选择从不检查更新并点击确定按钮,如图:
- LeetCode OJ:Binary Tree Zigzag Level Order Traversal(折叠二叉树遍历)
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to ...
- HttpClient与Spring RestTemplate
需要的包 ,除了Spring的基础包外还用到json的包,这里的数据传输使用json格式 客户端和服务端都用到一下的包 <!-- Spring --> <dependency> ...