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" }
)

猜你喜欢

转载自www.cnblogs.com/yhq1314/p/10008221.html
今日推荐