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

Azure Cosmos DB 是世纪互联提供的多区域分布式多模型数据库服务。Azure Cosmos DB is 21Vianet's multiple-regionally distributed multi-model database service. 可通过任何开源 MongoDB 客户端驱动程序与 Azure Cosmos DB 的 MongoDB API 进行通信。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 的用于 MongoDB 的 API,可以像以往一样从 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, automatic indexing of every field, encryption at rest, backups, and much more.

备注

本文适用于 Azure Cosmos DB 的 API for MongoDB 3.2。This article is for Azure Cosmos DB's API for MongoDB 3.2. 对于 MongoDB 3.6 版本,请参阅 MongoDB 3.6 支持的功能和语法For MongoDB 3.6 version, see MongoDB 3.6 supported features and syntax.

协议支持Protocol Support

Azure Cosmos DB 的 API for MongoDB 的所有新帐户都与 MongoDB 服务器版本 3.6 兼容。All new accounts for Azure Cosmos DB's API for MongoDB are compatible with MongoDB server version 3.6. 本文介绍 MongoDB 版本 3.2。This article covers MongoDB version 3.2. 支持的运算符以及限制或例外已列在下面。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.

查询语言支持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

  • deletedelete
  • findfind
  • findAndModifyfindAndModify
  • getLastErrorgetLastError
  • getMoregetMore
  • insertinsert
  • updateupdate

身份验证命令Authentication commands

  • logoutlogout
  • authenticateauthenticate
  • getnoncegetnonce

管理命令Administration commands

  • dropDatabasedropDatabase
  • listCollectionslistCollections
  • dropdrop
  • createcreate
  • filemd5filemd5
  • createIndexescreateIndexes
  • listIndexeslistIndexes
  • dropIndexesdropIndexes
  • connectionStatusconnectionStatus
  • reIndexreIndex

诊断命令Diagnostics commands

  • buildInfobuildInfo
  • collStatscollStats
  • dbStatsdbStats
  • hostInfohostInfo
  • listDatabaseslistDatabases
  • whatsmyuriwhatsmyuri

聚合管道Aggregation pipeline

在公共预览版中,Cosmos DB 支持 MongoDB 3.2 的聚合管道。Cosmos DB supports aggregation pipeline for MongoDB 3.2 in public preview. 请参阅 Azure 博客,了解有关如何载入到公共预览版的说明。See the Azure blog for instructions on how to onboard to the public preview.

聚合命令Aggregation commands

  • aggregateaggregate
  • countcount
  • distinctdistinct

聚合阶段Aggregation stages

  • $project$project
  • $match$match
  • $limit$limit
  • $skip$skip
  • $unwind$unwind
  • $group$group
  • $sample$sample
  • $sort$sort
  • $lookup$lookup
  • $out$out
  • $count$count
  • $addFields$addFields

聚合表达式Aggregation expressions

布尔表达式Boolean expressions

  • $and$and
  • $or$or
  • $not$not

集表达式Set expressions

  • $setEquals$setEquals
  • $setIntersection$setIntersection
  • $setUnion$setUnion
  • $setDifference$setDifference
  • $setIsSubset$setIsSubset
  • $anyElementTrue$anyElementTrue
  • $allElementsTrue$allElementsTrue

比较表达式Comparison expressions

  • $cmp$cmp
  • $eq$eq
  • $gt$gt
  • $gte$gte
  • $lt$lt
  • $lte$lte
  • $ne$ne

算术表达式Arithmetic expressions

  • $abs$abs
  • $add$add
  • $ceil$ceil
  • $divide$divide
  • $exp$exp
  • $floor$floor
  • $ln$ln
  • $log$log
  • $log10$log10
  • $mod$mod
  • $multiply$multiply
  • $pow$pow
  • $sqrt$sqrt
  • $subtract$subtract
  • $trunc$trunc

字符串表达式String expressions

  • $concat$concat
  • $indexOfBytes$indexOfBytes
  • $indexOfCP$indexOfCP
  • $split$split
  • $strLenBytes$strLenBytes
  • $strLenCP$strLenCP
  • $strcasecmp$strcasecmp
  • $substr$substr
  • $substrBytes$substrBytes
  • $substrCP$substrCP
  • $toLower$toLower
  • $toUpper$toUpper

数组表达式Array expressions

  • $arrayElemAt$arrayElemAt
  • $concatArrays$concatArrays
  • $filter$filter
  • $indexOfArray$indexOfArray
  • $isArray$isArray
  • $range$range
  • $reverseArray$reverseArray
  • $size$size
  • $slice$slice
  • $in$in

日期表达式Date expressions

  • $dayOfYear$dayOfYear
  • $dayOfMonth$dayOfMonth
  • $dayOfWeek$dayOfWeek
  • $year$year
  • $month$month
  • $week$week
  • $hour$hour
  • $minute$minute
  • $second$second
  • $millisecond$millisecond
  • $isoDayOfWeek$isoDayOfWeek
  • $isoWeek$isoWeek

条件表达式Conditional expressions

  • $cond$cond
  • $ifNull$ifNull

聚合累加器Aggregation accumulators

  • $sum$sum
  • $avg$avg
  • $first$first
  • $last$last
  • $max$max
  • $min$min
  • $push$push
  • $addToSet$addToSet

运算符Operators

以下运算符在其相应的使用示例中受支持。Following operators are supported with corresponding examples of their use. 请考虑下面的查询中使用的示例文档:Consider this sample document used in the queries below:

{
  "Volcano Name": "Rainier",
  "Country": "United States",
  "Region": "US-Washington",
  "Location": {
    "type": "Point",
    "coordinates": [
      -121.758,
      46.87
    ]
  },
  "Elevation": 4392,
  "Type": "Stratovolcano",
  "Status": "Dendrochronology",
  "Last Known Eruption": "Last known eruption from 1800-1899, inclusive"
}
操作员Operator 示例Example
$eq$eq { "Volcano Name": { $eq: "Rainier" } }
$gt$gt { "Elevation": { $gt: 4000 } }
$gte$gte { "Elevation": { $gte: 4392 } }
$lt$lt { "Elevation": { $lt: 5000 } }
$lte$lte { "Elevation": { $lte: 5000 } }
$ne$ne { "Elevation": { $ne: 1 } }
$in$in { "Volcano Name": { $in: ["St. Helens", "Rainier", "Glacier Peak"] } }
$nin$nin { "Volcano Name": { $nin: ["Lassen Peak", "Hood", "Baker"] } }
$or$or { $or: [ { Elevation: { $lt: 4000 } }, { "Volcano Name": "Rainier" } ] }
$and$and { $and: [ { Elevation: { $gt: 4000 } }, { "Volcano Name": "Rainier" } ] }
$not$not { "Elevation": { $not: { $gt: 5000 } } }
$nor$nor { $nor: [ { "Elevation": { $lt: 4000 } }, { "Volcano Name": "Baker" } ] }
$exists$exists { "Status": { $exists: true } }
$type$type { "Status": { $type: "string" } }
$mod$mod { "Elevation": { $mod: [ 4, 0 ] } }
$regex$regex { "Volcano Name": { $regex: "^Rain"} }

说明Notes

在 $regex 查询中,左定位表达式允许索引搜索。In $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$/}),必须按如下所示进行修改:find({x:{$regex: /^abc/, 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$/}}). 第一部分将使用索引将搜索限制为以 ^ 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/}] }).

更新运算符Update operators

字段更新运算符Field update operators

  • $inc$inc
  • $mul$mul
  • $rename$rename
  • $setOnInsert$setOnInsert
  • $set$set
  • $unset$unset
  • $min$min
  • $max$max
  • $currentDate$currentDate

数组更新运算符Array update operators

  • $addToSet$addToSet
  • $pop$pop
  • $pullAll$pullAll
  • $pull(注意:不支持带条件的 $pull)$pull (Note: $pull with condition is not supported)
  • $pushAll$pushAll
  • $push$push
  • $each$each
  • $slice$slice
  • $sort$sort
  • $position$position

位更新运算符Bitwise update operator

  • $bit$bit

地理空间运算符Geospatial operators

操作员Operator 示例Example
$geoWithin$geoWithin { "Location.coordinates": { $geoWithin: { $centerSphere: [ [ -121, 46 ], 5 ] } } } Yes
$geoIntersects$geoIntersects { "Location.coordinates": { $geoIntersects: { $geometry: { type: "Polygon", coordinates: [ [ [ -121.9, 46.7 ], [ -121.5, 46.7 ], [ -121.5, 46.9 ], [ -121.9, 46.9 ], [ -121.9, 46.7 ] ] ] } } } } Yes
$near$near { "Location.coordinates": { $near: { $geometry: { type: "Polygon", coordinates: [ [ [ -121.9, 46.7 ], [ -121.5, 46.7 ], [ -121.5, 46.9 ], [ -121.9, 46.9 ], [ -121.9, 46.7 ] ] ] } } } } Yes
$nearSphere$nearSphere { "Location.coordinates": { $nearSphere : [ -121, 46 ], $maxDistance: 0.50 } } Yes
$geometry$geometry { "Location.coordinates": { $geoWithin: { $geometry: { type: "Polygon", coordinates: [ [ [ -121.9, 46.7 ], [ -121.5, 46.7 ], [ -121.5, 46.9 ], [ -121.9, 46.9 ], [ -121.9, 46.7 ] ] ] } } } } Yes
$minDistance$minDistance { "Location.coordinates": { $nearSphere : { $geometry: {type: "Point", coordinates: [ -121, 46 ]}, $minDistance: 1000, $maxDistance: 1000000 } } } Yes
$maxDistance$maxDistance { "Location.coordinates": { $nearSphere : [ -121, 46 ], $maxDistance: 0.50 } } Yes
$center$center { "Location.coordinates": { $geoWithin: { $center: [ [-121, 46], 1 ] } } } Yes
$centerSphere$centerSphere { "Location.coordinates": { $geoWithin: { $centerSphere: [ [ -121, 46 ], 5 ] } } } Yes
$box$box { "Location.coordinates": { $geoWithin: { $box: [ [ 0, 0 ], [ -122, 47 ] ] } } } Yes
$polygon$polygon { "Location.coordinates": { $near: { $geometry: { type: "Polygon", coordinates: [ [ [ -121.9, 46.7 ], [ -121.5, 46.7 ], [ -121.5, 46.9 ], [ -121.9, 46.9 ], [ -121.9, 46.7 ] ] ] } } } } 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.

其他运算符Additional operators

操作员Operator 示例Example 说明Notes
$all$all { "Location.coordinates": { $all: [-121.758, 46.87] } }
$elemMatch$elemMatch { "Location.coordinates": { $elemMatch: { $lt: 0 } } }
$size$size { "Location.coordinates": { $size: 2 } }
$comment$comment { "Location.coordinates": { $elemMatch: { $lt: 0 } }, $comment: "Negative values"}
$text$text 不支持。Not supported. 改为使用 $regex。Use $regex instead.

不支持的运算符Unsupported operators

$where$eval 运算符不受 Azure Cosmos DB 支持。The $where and the $eval operators are not supported by Azure Cosmos DB.

方法Methods

支持下列方法:Following methods are supported:

游标方法Cursor methods

方法Method 示例Example 说明Notes
cursor.sort()cursor.sort() cursor.sort({ "Elevation": -1 }) 不会返回没有排序键的文件Documents without sort key do not get returned

唯一索引Unique indexes

默认情况下,Cosmos DB 为写入数据库的文档中的每个字段编制索引。Cosmos DB indexes every field in documents that are written to the database by default. 唯一索引确保特定字段在一个集合的所有文档中都不会有重复值,类似于默认 _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. 可以在 Cosmos DB 中使用 createIndex 命令(包括“唯一”约束)创建自定义索引。You can create custom indexes in Cosmos DB by using the createIndex command, including the 'unique' constraint.

所有使用 Azure Cosmos DB 的 MongoDB API 的 Cosmos 帐户都能使用唯一索引。Unique indexes are available for all Cosmos accounts using Azure Cosmos DB's API for MongoDB.

生存时间 (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 不支持手动分片命令,这意味着你不必调用 shardCollection、addShard、balancerStart、moveChunk 等命令。只需在创建容器或查询数据时指定分片键。Azure Cosmos DB does not support manual sharding commands, which means you don't have to invoke commands such as shardCollection, addShard, balancerStart, moveChunk etc. You only need to specify the shard key while creating the containers or querying the data.

后续步骤Next steps

  • 了解如何将 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.