Azure Cosmos DB 的 API for MongoDB(3.6 版本):支持的功能和语法Azure Cosmos DB's API for MongoDB (3.6 version): supported features and syntax

适用于: Azure Cosmos DB API for MongoDB

Azure Cosmos DB 是世纪互联提供的多区域分布式多模型数据库服务。Azure Cosmos DB is 21Vianet's multiple-regionally distributed multi-model database service. 可通过任何开源 MongoDB 客户端驱动程序与 Azure Cosmos DB's API for MongoDB 进行通信。You can communicate with the Azure Cosmos DB's API for MongoDB using any of the open-source MongoDB client drivers. 可以按照 MongoDB 有线协议规定,通过 Azure Cosmos DB 的 MongoDB API 来使用现有客户端驱动程序。The Azure Cosmos DB's API for MongoDB enables the use of existing client drivers by adhering to the MongoDB wire protocol.

通过使用 Azure Cosmos DB API for MongoDB,可以像以往一样从 MongoDB 中受益,并且可使用 Cosmos DB 提供的所有企业功能:多区域分布自动分片、可用性和延迟保证、静态加密和备份等。By using the Azure Cosmos DB's API for MongoDB, you can enjoy the benefits of the MongoDB you're used to, with all of the enterprise capabilities that Cosmos DB provides: multiple-region distribution, automatic sharding, availability and latency guarantees, encryption at rest, backups, and much more.

协议支持Protocol Support

默认情况下,对于新帐户,Azure Cosmos DB 的 API for MongoDB 与 MongoDB 服务器版本 3.6 兼容。The Azure Cosmos DB's API for MongoDB is compatible with MongoDB server version 3.6 by default for new accounts. 支持的运算符以及限制或例外已列在下面。The supported operators and any limitations or exceptions are listed below. 任何理解这些协议的客户端驱动程序应该都能够连接到 Azure Cosmos DB 的 MongoDB API。Any client driver that understands these protocols should be able to connect to Azure Cosmos DB's API for MongoDB. 请注意,使用 Azure Cosmos DB's API for MongoDB 帐户时,3.6 版的帐户的终结点格式为 *.mongo.cosmos.azure.cn,而 3.2 版的帐户的终结点格式为 *.documents.azure.cnNote that when using Azure Cosmos DB's API for MongoDB accounts, the 3.6 version of accounts have the endpoint in the format *.mongo.cosmos.azure.cn whereas the 3.2 version of accounts have the endpoint in the format *.documents.azure.cn.

查询语言支持Query language support

Azure Cosmos DB 的 MongoDB API 全面支持 MongoDB 查询语言构造。Azure Cosmos DB's API for MongoDB provides comprehensive support for MongoDB query language constructs. 可以在下面查找当前支持的操作、运算符、阶段、命令和选项的详细列表。Below you can find the detailed list of currently supported operations, operators, stages, commands, and options.

数据库命令Database commands

Azure Cosmos DB 的 MongoDB API 支持以下数据库命令:Azure Cosmos DB's API for MongoDB supports the following database commands:

查询和写入操作命令Query and write operation commands

CommandCommand 支持Supported
deletedelete Yes
findfind Yes
findAndModifyfindAndModify Yes
getLastErrorgetLastError Yes
getMoregetMore Yes
getPrevErrorgetPrevError No
insertinsert Yes
parallelCollectionScanparallelCollectionScan Yes
resetErrorresetError No
updateupdate Yes
更改流Change streams Yes
GridFSGridFS Yes

身份验证命令Authentication commands

CommandCommand 支持Supported
authenticateauthenticate Yes
logoutlogout Yes
getnoncegetnonce Yes

管理命令Administration commands

CommandCommand 支持Supported
Capped CollectionsCapped Collections No
cloneCollectionAsCappedcloneCollectionAsCapped No
collModcollMod No
collMod: expireAfterSecondscollMod: expireAfterSeconds No
convertToCappedconvertToCapped No
copydbcopydb No
createcreate Yes
createIndexescreateIndexes Yes
currentOpcurrentOp Yes
dropdrop Yes
dropDatabasedropDatabase Yes
dropIndexesdropIndexes Yes
filemd5filemd5 Yes
killCursorskillCursors Yes
killOpkillOp No
listCollectionslistCollections Yes
listDatabaseslistDatabases Yes
listIndexeslistIndexes Yes
reIndexreIndex Yes
renameCollectionrenameCollection No
connectionStatusconnectionStatus No

诊断命令Diagnostics commands

CommandCommand 支持Supported
buildInfobuildInfo Yes
collStatscollStats Yes
connPoolStatsconnPoolStats No
connectionStatusconnectionStatus No
dataSizedataSize No
dbHashdbHash No
dbStatsdbStats Yes
explainexplain Yes
explain: executionStatsexplain: executionStats Yes
featuresfeatures No
hostInfohostInfo No
listDatabaseslistDatabases Yes
listCommandslistCommands No
profilerprofiler No
serverStatusserverStatus No
toptop No
whatsmyuriwhatsmyuri Yes

聚合管道Aggregation pipeline

聚合命令Aggregation commands

CommandCommand 支持Supported
aggregateaggregate Yes
countcount Yes
distinctdistinct Yes
mapReducemapReduce No

聚合阶段Aggregation stages

CommandCommand 支持Supported
$collStats$collStats No
$project$project Yes
$match$match Yes
$redact$redact Yes
$limit$limit Yes
$skip$skip Yes
$unwind$unwind Yes
$group$group Yes
$sample$sample Yes
$sort$sort Yes
$geoNear$geoNear No
$lookup$lookup Yes
$out$out Yes
$indexStats$indexStats No
$facet$facet Yes
$bucket$bucket No
$bucketAuto$bucketAuto No
$sortByCount$sortByCount Yes
$addFields$addFields Yes
$replaceRoot$replaceRoot Yes
$count$count Yes
$currentOp$currentOp No
$listLocalSessions$listLocalSessions No
$listSessions$listSessions No
$graphLookup$graphLookup No

布尔表达式Boolean expressions

CommandCommand 支持Supported
$and$and Yes
$or$or Yes
$not$not Yes

集表达式Set expressions

CommandCommand 支持Supported
$setEquals$setEquals Yes
$setIntersection$setIntersection Yes
$setUnion$setUnion Yes
$setDifference$setDifference Yes
$setIsSubset$setIsSubset Yes
$anyElementTrue$anyElementTrue Yes
$allElementsTrue$allElementsTrue Yes

比较表达式Comparison expressions

CommandCommand 支持Supported
$cmp$cmp Yes
$eq$eq Yes
$gt$gt Yes
$gte$gte Yes
$lt$lt Yes
$lte$lte Yes
$ne$ne Yes
$in$in Yes
$nin$nin Yes

算术表达式Arithmetic expressions

CommandCommand 支持Supported
$abs$abs Yes
$add$add Yes
$ceil$ceil Yes
$divide$divide Yes
$exp$exp Yes
$floor$floor Yes
$ln$ln Yes
$log$log Yes
$log10$log10 Yes
$mod$mod Yes
$multiply$multiply Yes
$pow$pow Yes
$sqrt$sqrt Yes
$subtract$subtract Yes
$trunc$trunc Yes

字符串表达式String expressions

CommandCommand 支持Supported
$concat$concat Yes
$indexOfBytes$indexOfBytes Yes
$indexOfCP$indexOfCP Yes
$split$split Yes
$strLenBytes$strLenBytes Yes
$strLenCP$strLenCP Yes
$strcasecmp$strcasecmp Yes
$substr$substr Yes
$substrBytes$substrBytes Yes
$substrCP$substrCP Yes
$toLower$toLower Yes
$toUpper$toUpper Yes

文本搜索运算符Text search operator

CommandCommand 支持Supported
$meta$meta No

数组表达式Array expressions

CommandCommand 支持Supported
$arrayElemAt$arrayElemAt Yes
$arrayToObject$arrayToObject Yes
$concatArrays$concatArrays Yes
$filter$filter Yes
$indexOfArray$indexOfArray Yes
$isArray$isArray Yes
$objectToArray$objectToArray Yes
$range$range Yes
$reverseArray$reverseArray Yes
$reduce$reduce Yes
$size$size Yes
$slice$slice Yes
$zip$zip Yes
$in$in Yes

变量运算符Variable operators

CommandCommand 支持Supported
$map$map No
$let$let Yes

系统变量System variables

CommandCommand 支持Supported
$$CURRENT$$CURRENT Yes
$$DESCEND$$DESCEND Yes
$$KEEP$$KEEP Yes
$$PRUNE$$PRUNE Yes
$$REMOVE$$REMOVE Yes
$$ROOT$$ROOT Yes

文本运算符Literal operator

CommandCommand 支持Supported
$literal$literal Yes

日期表达式Date expressions

CommandCommand 支持Supported
$dayOfYear$dayOfYear Yes
$dayOfMonth$dayOfMonth Yes
$dayOfWeek$dayOfWeek Yes
$year$year Yes
$month$month Yes
$week$week Yes
$hour$hour Yes
$minute$minute Yes
$second$second Yes
$millisecond$millisecond Yes
$dateToString$dateToString Yes
$isoDayOfWeek$isoDayOfWeek Yes
$isoWeek$isoWeek Yes
$dateFromParts$dateFromParts No
$dateToParts$dateToParts No
$dateFromString$dateFromString No
$isoWeekYear$isoWeekYear Yes

条件表达式Conditional expressions

CommandCommand 支持Supported
$cond$cond Yes
$ifNull$ifNull Yes
$switch$switch Yes

数据类型运算符Data type operator

CommandCommand 支持Supported
$type$type Yes

累加器表达式Accumulator expressions

CommandCommand 支持Supported
$sum$sum Yes
$avg$avg Yes
$first$first Yes
$last$last Yes
$max$max Yes
$min$min Yes
$push$push Yes
$addToSet$addToSet Yes
$stdDevPop$stdDevPop No
$stdDevSamp$stdDevSamp No

合并运算符Merge operator

CommandCommand 支持Supported
$mergeObjects$mergeObjects Yes

数据类型Data types

CommandCommand 支持Supported
DoubleDouble Yes
字符串String Yes
对象Object Yes
ArrayArray Yes
Binary DataBinary Data Yes
ObjectIdObjectId Yes
BooleanBoolean Yes
DateDate Yes
NullNull Yes
32 位整数 (int)32-bit Integer (int) Yes
时间戳Timestamp Yes
64 位整数 (long)64-bit Integer (long) Yes
MinKeyMinKey Yes
MaxKeyMaxKey Yes
Decimal128Decimal128 Yes
Regular ExpressionRegular Expression Yes
JavaScriptJavaScript Yes
JavaScript(带范围)JavaScript (with scope) Yes
UndefinedUndefined Yes

索引和索引属性Indexes and index properties

索引Indexes

CommandCommand 支持Supported
单字段索引Single Field Index Yes
复合索引Compound Index Yes
多键索引Multikey Index Yes
文本索引Text Index No
2dsphere2dsphere Yes
2d 索引2d Index No
哈希索引Hashed Index Yes

索引属性Index properties

CommandCommand 支持Supported
TTLTTL Yes
唯一Unique Yes
部分Partial No
不区分大小写Case Insensitive No
稀疏Sparse No
背景Background Yes

运算符Operators

逻辑运算符Logical operators

CommandCommand 支持Supported
$or$or Yes
$and$and Yes
$not$not Yes
$nor$nor Yes

元素运算符Element operators

CommandCommand 支持Supported
$exists$exists Yes
$type$type Yes

评估查询运算符Evaluation query operators

CommandCommand 支持Supported
$expr$expr No
$jsonSchema$jsonSchema No
$mod$mod Yes
$regex$regex Yes
$text$text 否(不支持。No (Not supported. 请改用 $regex。)Use $regex instead.)
$where$where No

在 $regex 查询中,左定位表达式允许索引搜索。In the $regex queries, left-anchored expressions allow index search. 但是,使用“i”修饰符(不区分大小写)和“m”修饰符(多行)会导致在所有表达式中进行回收集合扫描。However, using 'i' modifier (case-insensitivity) and 'm' modifier (multiline) causes the collection scan in all expressions.

当需要包含“$”或“|”时,最好创建两个(或更多)正则表达式查询。When there's a need to include '$' or '|', it is best to create two (or more) regex queries. 例如,给定以下原始查询:find({x:{$regex: /^abc$/}),必须按如下所示进行修改:For example, given the following original query: find({x:{$regex: /^abc$/}), it has to be modified as follows:

find({x:{$regex: /^abc/, x:{$regex:/^abc$/}}) 列中的一个值匹配。find({x:{$regex: /^abc/, x:{$regex:/^abc$/}}).

第一部分将使用索引将搜索限制为以 ^ abc 开头的文档,第二部分将匹配确切的条目。The first part will use the index to restrict the search to those documents beginning with ^abc and the second part will match the exact entries. 竖条运算符“|”充当“or”函数 - 查询 find({x:{$regex: /^abc|^def/}) 匹配字段“x”的值以“abc”或“def”开头的文档。The bar operator '|' acts as an "or" function - the query find({x:{$regex: /^abc|^def/}) matches the documents in which field 'x' has values that begin with "abc" or "def". 要使用索引,建议将查询分解为两个由 $or 运算符连接的不同查询:find( {$or : [{x: $regex: /^abc/}, {$regex: /^def/}] })To utilize the index, it's recommended to break the query into two different queries joined by the $or operator: find( {$or : [{x: $regex: /^abc/}, {$regex: /^def/}] }).

数组运算符Array operators

CommandCommand 支持Supported
$all$all Yes
$elemMatch$elemMatch Yes
$size$size Yes

注释运算符Comment operator

CommandCommand 支持Supported
$comment$comment Yes

投影运算符Projection operators

CommandCommand 支持Supported
$elemMatch$elemMatch Yes
$meta$meta No
$slice$slice Yes

更新运算符Update operators

字段更新运算符Field update operators

CommandCommand 支持Supported
$inc$inc Yes
$mul$mul Yes
$rename$rename Yes
$setOnInsert$setOnInsert Yes
$set$set Yes
$unset$unset Yes
$min$min Yes
$max$max Yes
$currentDate$currentDate Yes

数组更新运算符Array update operators

CommandCommand 支持Supported
$ Yes
$[]$[] Yes
$[]$[] Yes
$addToSet$addToSet Yes
$pop$pop Yes
$pullAll$pullAll Yes
$pull$pull Yes
$push$push Yes
$pushAll$pushAll Yes

更新修饰符Update modifiers

CommandCommand 支持Supported
$each$each Yes
$slice$slice Yes
$sort$sort Yes
$position$position Yes

位更新运算符Bitwise update operator

CommandCommand 支持Supported
$bit$bit Yes
$bitsAllSet$bitsAllSet No
$bitsAnySet$bitsAnySet No
$bitsAllClear$bitsAllClear No
$bitsAnyClear$bitsAnyClear No

地理空间运算符Geospatial operators

操作员Operator 支持Supported
$geoWithin$geoWithin Yes
$geoIntersects$geoIntersects Yes
$near$near Yes
$nearSphere$nearSphere Yes
$geometry$geometry Yes
$minDistance$minDistance Yes
$maxDistance$maxDistance Yes
$center$center No
$centerSphere$centerSphere No
$box$box No
$polygon$polygon No

游标方法Cursor methods

CommandCommand 支持Supported
cursor.batchSize()cursor.batchSize() Yes
cursor.close()cursor.close() Yes
cursor.isClosed()cursor.isClosed() Yes
cursor.collation()cursor.collation() No
cursor.comment()cursor.comment() Yes
cursor.count()cursor.count() Yes
cursor.explain()cursor.explain() No
cursor.forEach()cursor.forEach() Yes
cursor.hasNext()cursor.hasNext() Yes
cursor.hint()cursor.hint() Yes
cursor.isExhausted()cursor.isExhausted() Yes
cursor.itcount()cursor.itcount() Yes
cursor.limit()cursor.limit() Yes
cursor.map()cursor.map() Yes
cursor.maxScan()cursor.maxScan() Yes
cursor.maxTimeMS()cursor.maxTimeMS() Yes
cursor.max()cursor.max() Yes
cursor.min()cursor.min() Yes
cursor.next()cursor.next() Yes
cursor.noCursorTimeout()cursor.noCursorTimeout() No
cursor.objsLeftInBatch()cursor.objsLeftInBatch() Yes
cursor.pretty()cursor.pretty() Yes
cursor.readConcern()cursor.readConcern() Yes
cursor.readPref()cursor.readPref() Yes
cursor.returnKey()cursor.returnKey() No
cursor.showRecordId()cursor.showRecordId() No
cursor.size()cursor.size() Yes
cursor.skip()cursor.skip() Yes
cursor.sort()cursor.sort() Yes
cursor.tailable()cursor.tailable() No
cursor.toArray()cursor.toArray() Yes

排序运算符Sort operations

使用 findOneAndUpdate 操作时,支持基于单个字段的排序操作,但不支持基于多个字段的排序操作。When using the findOneAndUpdate operation, sort operations on a single field are supported but sort operations on multiple fields are not supported.

唯一索引Unique indexes

唯一索引确保特定字段在一个集合的所有文档中都不会有重复值,类似于默认“_id”键上保持唯一性的方式。Unique indexes ensure that a specific field doesn't have duplicate values across all documents in a collection, similar to the way uniqueness is preserved on the default "_id" key. 可以通过将 createIndex 命令与 unique 约束参数一起使用,在 Cosmos DB 中创建唯一索引:You can create unique indexes in Cosmos DB by using the createIndex command with the unique constraint parameter:

globaldb:PRIMARY> db.coll.createIndex( { "amount" : 1 }, {unique:true} )
{
        "_t" : "CreateIndexesResponse",
        "ok" : 1,
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 4
}

复合索引Compound indexes

复合索引提供一种为多达 8 个字段的字段组创建索引的方法。Compound indexes provide a way to create an index for groups of fields for up to 8 fields. 此类型的索引不同于本机 MongoDB 复合索引。This type of index differs from the native MongoDB compound indexes. 在 Azure Cosmos DB 中,复合索引用于对应用于多个字段的操作进行排序。In Azure Cosmos DB, compound indexes are used for sorting operations that are applied to multiple fields. 若要创建复合索引,需要指定多个属性作为参数:To create a compound index you need to specify more than one property as the parameter:

globaldb:PRIMARY> db.coll.createIndex({"amount": 1, "other":1})
{
        "createdCollectionAutomatically" : false, 
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

生存时间 (TTL)Time-to-live (TTL)

Cosmos DB 支持基于文档时间戳的生存时间 (TTL)。Cosmos DB supports a time-to-live (TTL) based on the timestamp of the document. 转到 Azure 门户便可以为集合启用 TTL。TTL can be enabled for collections by going to the Azure portal.

用户和角色管理User and role management

Cosmos DB 尚不支持用户和角色。Cosmos DB does not yet support users and roles. 不过 Cosmos DB 支持基于角色的访问控制 (RBAC) 以及读写和只读密码/密钥,可通过 Azure 门户(连接字符串页面)获取这些内容。However, Cosmos DB supports role-based access control (RBAC) and read-write and read-only passwords/keys that can be obtained through the Azure portal (Connection String page).

复制Replication

Cosmos DB 支持在最低层进行自动本机复制。Cosmos DB supports automatic, native replication at the lowest layers. 此逻辑还可以扩展,实现低延迟的多区域复制。This logic is extended out to achieve low-latency, multiple-region replication as well. 它不支持手动复制命令。Cosmos DB does not support manual replication commands.

写关注Write Concern

某些应用程序依赖写关注,后者指定写入操作期间需要的响应数。Some applications rely on a Write Concern which specifies the number of responses required during a write operation. 考虑到 Cosmos DB 在后台处理复制的方式,所有写入默认情况下都自动成为仲裁。Due to how Cosmos DB handles replication in the background all writes are all automatically Quorum by default. 由客户端代码指定的任何写关注都会被系统忽略。Any write concern specified by the client code is ignored. 有关详细信息,请参阅使用一致性级别最大化可用性和性能Learn more in Using consistency levels to maximize availability and performance.

分片Sharding

Azure Cosmos DB 支持服务器端自动分片。Azure Cosmos DB supports automatic, server-side sharding. 它自动管理分片的创建、放置和均衡。It manages shard creation, placement, and balancing automatically. Azure Cosmos DB 不支持手动分片命令,这意味着你不必调用 addShard、balancerStart、moveChunk 等命令。只需在创建容器或查询数据时指定分片键。Azure Cosmos DB does not support manual sharding commands, which means you don't have to invoke commands such as addShard, balancerStart, moveChunk etc. You only need to specify the shard key while creating the containers or querying the data.

会话Sessions

Azure Cosmos DB 尚不支持服务器端会话命令。Azure Cosmos DB does not yet support server side sessions commands.

后续步骤Next steps

  • 有关详细信息,请查看 Mongo 3.6 版本功能For further information check Mongo 3.6 version features
  • 了解如何将 Studio 3T 与 Azure Cosmos DB 的用于 MongoDB 的 API 配合使用。Learn how to use Studio 3T with Azure Cosmos DB's API for MongoDB.
  • 了解如何将 Robo 3T 与 Azure Cosmos DB 的用于 MongoDB 的 API 配合使用。Learn how to use Robo 3T with Azure Cosmos DB's API for MongoDB.
  • 使用 Azure Cosmos DB 的用于 MongoDB 的 API 浏览 MongoDB 示例Explore MongoDB samples with Azure Cosmos DB's API for MongoDB.

注意:本文介绍了可与 MongoDB 数据库实现线路协议兼容的 Azure Cosmos DB 功能。Azure 不会运行 MongoDB 数据库来提供此服务。Azure Cosmos DB 并不隶属于 MongoDB, inc.Note: This article describes a feature of Azure Cosmos DB that provides wire protocol compatibility with MongoDB databases. Azure does not run MongoDB databases to provide this service. Azure Cosmos DB is not affiliated with MongoDB, Inc.