MongoDB - 集合方法

MongoDB - 集合方法 首页 / MongoDB入门教程 / MongoDB - 集合方法

以下是在不同方案中使用的MongoDB收集方法。

db.collection.aggregate(pipeline,option)

聚合方法计算集合或视图中数据的值。

Pipeline       - 它是一系列数据操作。它可以接受管道作为单独的参数,而不是数组中的元素。如果未指定管道作为数组,则不会指定第二个参数。

Option         -  传递聚合命令的文档。只有当您将管道指定为数组时,它只可用。

命令字段:

字段类型说明
explainboolean返回有关管道处理的信息。
allowDiskUseboolean可以写入临时文件。
cursordocument使用此字段指定光标的初始批处理大小。此字段内的值是带有batchSize字段的文档。
maxTimeMS非负整数使用此字段指定在光标上进行处理操作的时间限制。
bypassDocumentValidation boolean可以使用此字段指定$out或$merge聚合操作过程中绕过文档验证。
readConcerndocument您可以在此字段中指定读取级别。
collationdocument排序规则字段指定用于字符串比较的特定于语言的规则。

示例

这些示例使用包含以下文档的集合库:

{ _id: 1, book_id: "Java", ord_date: ISODate("2012-11-02T17:04:11.102Z"), status: "A", amount: 50 }
{ _id: 0, book_id: "MongoDB", ord_date: ISODate("2013-10-01T17:04:11.102Z"), status: "A", amount: 100 }
{ _id: 0.01, book_id: "DBMS", ord_date: ISODate("2013-10-12T17:04:11.102Z"), status: "D", amount: 25 }
{ _id: 2, book_id: "Python", ord_date: ISODate("2013-10-11T17:04:11.102Z"), status: "D", amount: 125 }
{ _id: 0.02, book_id: "SQL", ord_date: ISODate("2013-11-12T17:04:11.102Z"), status: "A", amount: 25 }

计算总和

db.library.aggregate([
                     { $match: { status: "A" } },
                     { $group: { _id: "$book_id", total: { $count: "$amount" } } },
                     { $sort: { total: -1 } }
                   ])

输出:

MongoDB Shell Collection Methods

指定排序规则

db.library.aggregate(
   [ { $match: { status: "A" } }, { $group: { _id: "$ord_date", count: { $count: 1 } } } ],
   { library: { locale: "fr", strength: 1 } } );

db.collection.bulkWrite()

bulkWrite()方法按照执行控制的顺序执行多个写入操作。写入操作数组由该操作执行。默认情况下,操作以特定顺序执行。

语法:

db.collection.bulkWrite(
   [ <op. 1>, <op. 2>, .. ],
   {
      writeConcern : <document>,
      ordered: <boolean>
   }
)

输出:

MongoDB Shell Collection Methods

执行运算符

insertOne   -  它仅将一个文档插入到集合中。

db.collection.bulkWrite( [
   { insertOne : { "document" : <document> } }
] )
MongoDB Shell Collection Methods

Update one   -  它仅更新一个与集合中的过滤器匹配的文档。

db.collection.bulkWrite( [
   { updateOne :
      {
         "filter": <document>,
         "update": <document or pipeline>,
         "upsert": <boolean>,
         "collation": <document>,
         "arrayFilters": [ <filterdocument1>, ... ],
         "hint": <document|string>
      }
   }
] )

输出:

MongoDB Shell Collection Methods

Update Many   - 它将更新集合中所有与过滤条件匹配的文档。

db.collection.bulkWrite( [
   { updateMany :{
         "filter" : <doc.>,
         "update" : <document or pipeline>,          
         "upsert" : <Boolean>,
         "collation": <document>,           
         "arrayFilters": [ <filterdocument1>, ... ], 
         "hint": <document|string>                  //Available starting in 4.2.1
      }
   }
] )

replaceOne  -  它将替换集合中与过滤器匹配的单个文档。

db.collection.bulkWrite([
{ replaceOne :
 {
    "filter" : <doc.>,
     "replacement" : <doc.>,
     "upsert" : <boolean>,
     "collation": <document>,
     "hint": <document|string>
   }
 }
] )

db.collection.count(query,options)

count()方法返回与集合或视图的find方法查询匹配的文档数。

无涯教程将使用以下操作对learnfk集合中的所有文档进行计数:

db.learnfk.count()

现在,无涯教程将计算learnfk集合中与查询匹配的所有文档,其中tut_dt字段大于新日期('01/01/2015')

db.learnfk.count( { tut_dt: { $gt: new Date('01/01/2015') } } )

输出:

MongoDB Shell Collection Methods

db.collection.countDocuments(query,options)

countDocument()方法返回与集合或视图的查询相匹配的文档数。它不使用元数据返回计数。

语法:

db.collection.countDocuments( <query>, <options> )

示例:  下面的示例将计算learnfk集合中所有文档的数量。

db.learnfk.countDocuments({})

现在,无涯教程将计算learnfk集合中与查询匹配的所有文档,其中tut_dt字段大于新日期('01/01/2015')

db.learnfk.countDocuments( { tut_dt: { $gt: new Date('01/01/2015') } } )

db.collection.estimatedDocumentCount()

估计DocumentCount()方法在集合或视图中计算所有文档。此方法包裹Count命令。

语法:

db.collection.estimatedDocumentCount( <options> )

示例:  以下示例将检索 learnfk 集合中所有文档的计数:

db.learnfk.estimatedDocumentCount({})

db.collection.createIndex()

它可以在集合上创建索引

语法:

db.collection.createIndex(keys, options)

keys :对于字段的升序索引,无涯教程需要指定值1,对于降序索引,无涯教程需要指定值-1。

示例

下面的示例在字段tut_Date上创建一个升序索引。

db.collection.createIndex( { tut_Date: 1 } )

以下示例显示在TUT_DATE字段和TUT_CODE字段上创建的复合索引。

db.collection.createIndex( { tut_Date: 1, tut_code: -1 } )

下面的示例将创建一个名为category_tutorial的索引。该示例使用指定语言环境fr和比较强度的排序规则创建索引。

无涯教程网

db.collection.createIndex(
   { category: 1 },
   { name: "category_tutorial", collation: { locale: "fr", strength: 2 } }
)

db.collection.createIndexes()

createIndexes()方法在集合上创建一个或多个索引。

语法:

db.collection.createIndexes( [keyPatterns, ]options)

Keypatterns -  包含索引特定文档的数组。所有文档都有字段-值对。对于字段的升序索引,无涯教程需要指定值1,对于降序索引,无涯教程需要指定值-1

示例

在下面的示例中,无涯教程考虑了一个员工集合,其中包含类似于以下内容的文档:

{
   location: {
      type: "Point",
      coordinates: [-73.8577, 40.8447]
   },
   name: "Employee",
   company: "Amazon",
   borough: "CA",
}

上面的索引使用排序规范,该归属指定基本FR和比较强度为2。

db.products.createIndexes( [ { "manufacturer": 1}, { "category": 1 } ],
   { collation: { locale: "fr", strength: 2 } })

db.collection.deleteOne()

deleteOne()方法从集合中删除一个文档。它替换了与过滤器相似的第一个文档。您需要使用与唯一索引(例如id)相关的字段,以实现删除。

语法:

db.collection.deleteOne(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)

示例:  订单集合包含具有以下结构的文档:

{
   _id: objectId("563237a41a4d6859da"),
   book: "",
   qty: 2,
   type: "buy-limit",
   limit: 10,
   creationts: ISODate("2015-11-01T2:30:15Z"),
   expiryts: ISODate("2015-11-01T2:35:15Z"),
   client: "Learnfk"
}

以下操作删除带有_id的订单:objectId(" 563237a41a4d6858 2da"):

try {
   db.orders.deleteOne( { "_id" : objectId("563237a41a4d68582da") } );
} catch (e) {
   print(e);
}

输出:

MongoDB Shell Collection Methods

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

零基础学Python -〔尹会生〕

深入剖析Kubernetes -〔张磊〕

技术管理案例课 -〔许健〕

高楼的性能工程实战课 -〔高楼〕

容量保障核心技术与实战 -〔吴骏龙〕

数据分析思维课 -〔郭炜〕

AI大模型之美 -〔徐文浩〕

结构会议力 -〔李忠秋〕

Midjourney入门实践课 -〔Jovi〕

好记忆不如烂笔头。留下您的足迹吧 :)