Docs HomeMongoDB Shell

Compatibility Changes with Legacy mongo Shell与传统mongo Shell的兼容性更改

This page describes differences between mongosh and the legacy mongo shell. 本页描述了mongosh和传统mongoshell之间的差异。In addition to the alternatives listed here, you can use the mongocompat snippet to access to legacy mongo shell APIs. 除了这里列出的备选方案外,您还可以使用mongocompat代码段访问遗留的mongoSnippets are an experimental feature, for more information, see Snippets.代码段是一个实验性功能,有关详细信息,请参阅Snippets

snippet install mongocompat

Deprecated Methods不推荐的方法

The following shell methods are deprecated in mongosh. mongosh中不赞成使用以下shell方法。Instead, use the methods listed in the Alternative Resources column.相反,请使用“替代资源”列中列出的方法。

Deprecated Method弃用的方法Alternative Resources替代资源
db.collection.copyTo()Aggregation stage: 聚合阶段:$out
db.collection.count()
db.collection.insert()
db.collection.remove()
db.collection.save()
db.collection.update()
DBQuery.shellBatchSize
Mongo.getSecondaryOkMongo.getReadPrefMode()
Mongo.isCausalConsistencySession.getOptions()
Mongo.setSecondaryOkMongo.setReadPref()
rs.secondaryOkNo longer required. 不再需要。See Read Operations on a Secondary Node.请参阅辅助节点上的读取操作

Read Preference Behavior读取首选项行为

Read Operations on a Secondary Node辅助节点上的读取操作

When using the legacy mongo shell to connect directly to secondary replica set member, you must run mongo.setReadPref() to enable secondary reads.当使用旧式mongoshell直接连接到secondary副本集成员时,必须运行mongo.setReadPref()才能启用辅助读取。

When using mongosh to connect directly to a secondary replica set member, you can read from that member if you specify a read preference of either:使用mongosh直接连接到secondary副本集成员时,如果指定以下任一读取首选项,则可以从该成员读取:

To specify a read preference, you can use either:要指定读取首选项,可以使用以下任一项:

When using mongosh to connect directly to a secondary replica set member, if your read preference is set to primaryPreferred, secondary or secondaryPreferred it is not required to run rs.secondaryOk().使用mongosh直接连接到secondary副本集成员时,如果您的读取首选项设置为primaryPreferredsecondarysecondaryPreferred,则不需要运行rs.secondaryOk()

show Helper Methods帮助方法

The following show helper methods always use a read preference of primaryPreferred, even when a different read preference has been specified for the operation:以下show helper方法始终使用primaryPreferred的读取首选项,即使为操作指定了不同的读取首项:

  • show dbs
  • show databases
  • show collections
  • show tables

In the legacy mongo shell, these operations use the specified read preference.在遗留的mongoshell中,这些操作使用指定的读取首选项。

Write Preference Behavior写入首选项行为

Retryable writes are enabled by default in mongosh. mongosh中默认启用可重试写入Retryable writes were disabled by default in the legacy mongo shell. 在旧版mongo shell中,默认情况下禁用了可重试写入。To disable retryable writes, use --retryWrites=false.若要禁用可重试写入,请使用--retryWrites=false

ObjectId Methods and AttributesObjectId方法和属性

These ObjectId() methods work differently in mongosh than in the legacy mongo shell.这些ObjectId()方法在mongosh中的工作方式与在传统mongoshell中的不同。

Method or Attribute方法或属性mongo Behaviormongosh Behavior
ObjectId.strReturns a hexadecimal string:返回一个十六进制字符串:
6419ccfce40afaf9317567b7
Undefined
(Not available)
ObjectId.valueOf()Returns the value of ObjectId.str:返回ObjectId.str的值:
6419ccfce40afaf9317567b7
Returns a formatted string:返回格式化的字符串:ObjectId("6419ccfce40afaf9317567b7")
ObjectId.toString()Returns a formatted string:返回格式化的字符串:
ObjectId("6419ccfce40afaf9317567b7")
Returns a hexadecimal formatted string:返回十六进制格式的字符串:
6419ccfce40afaf9317567b7

Numeric Values数值

The legacy mongo shell stored numerical values as doubles by default. 传统的mongoshell默认情况下将数值存储为doublesIn mongosh numbers are stored as 32 bit integers, Int32, or else as Double if the value cannot be stored as an Int32.mongosh中,数字存储为32位整数、Int32,如果值不能存储为Int32,则存储为Double

MongoDB Shell continues to support the numeric types that are supported in mongo shell. MongoDB Shell继续支持mongo Shell中支持的数字类型。However, the preferred types have been updated to better align with the MongoDB drivers. 然而,首选类型已经更新,以更好地与MongoDB驱动程序保持一致。See mongosh Data Types for more information.有关详细信息,请参阅mongosh数据类型

The preferred types for numeric variables are different in MongoDB Shell than the types suggested in the legacy mongo shell. MongoDB Shell中数字变量的首选类型与传统mongo Shell中建议的类型不同。The types in mongosh better align with the types used by the MongoDB Drivers.mongosh中的类型更好地与MongoDB驱动程序使用的类型保持一致。

mongo typemongosh type
NumberIntInt32
NumberLongLong
NumberDecimalDecimal128
Warning

Data types may be stored inconsistently if you connect to the same collection using both mongosh and the legacy mongo shell.如果同时使用mongosh和遗留mongoshell连接到同一集合,则数据类型的存储可能不一致。

Tip

See also:

For more information on managing types, refer to the schema validation overview.有关管理类型的更多信息,请参阅架构验证概述

--eval Behavior行为

mongosh --eval does not quote object keys in its ouptut.在其组中不引用对象键。

To get output suitable for automated parsing, use EJSON.stringify().要获得适合自动解析的输出,请使用EJSON.stringify()

mongosh --quiet  --host rs0/centos1104 --port 27500 \
--eval "EJSON.stringify(rs.status().members.map( \
m => ({'id':m._id, 'name':m.name, 'stateStr':m.stateStr})));" \
| jq

After parsing with jq, the output resembles this:使用jq进行解析后,输出类似于以下内容:

[
{
"id": 0,
"name": "centos1104:27500",
"stateStr": "PRIMARY"
},
{
"id": 1,
"name": "centos1104:27502",
"stateStr": "SECONDARY"
},
{
"id": 2,
"name": "centos1104:27503",
"stateStr": "SECONDARY"
}
]
Note

EJSON has built in formatting options which may eliminate the need for a parser like jq. 内置了格式化选项,可以消除对像jq这样的解析器的需求。For example, the following code produces output that is formatted the same as above.例如,下面的代码生成的输出格式与上面相同。

mongosh --quiet  --host rs0/centos1104 --port 27500 \
--eval "EJSON.stringify( rs.status().members.map( \
({ _id, name, stateStr }) => ({ _id, name, stateStr })), null, 2);"

Limitations on Database Calls数据库调用的限制

The results of database queries cannot be passed inside the following contexts:数据库查询的结果不能在以下上下文中传递:

  • Class constructor functions类构造函数函数
  • Non-async generator functions非异步生成器函数
  • Callbacks to .sort() on an array回调到数组上的.sort()

To access to the results of database calls, use async functions, async generator functions, or .map().要访问数据库调用的结果,请使用异步函数异步生成器函数.map()

Constructors构造函数

The following constructors do not work:以下构造函数不起作用:

// This code will fail
class FindResults {
constructor() {
this.value = db.students.find();
}
}

// This code will fail
function listEntries() { return db.students.find(); }
class FindResults {
constructor() {
this.value = listEntries();
}
}

Use an async function instead:请改用async函数:

class FindResults {
constructor() {
this.value = ( async() => {
return db.students.find();
} )();
}
}
Note

You can also create a method that performs a database operation inside a class as an alternative to working with asynchronous JavaScript.您还可以创建一个在类中执行数据库操作的方法,作为使用异步JavaScript的替代方法。

class FindResults {
constructor() { }

init() { this.value = db.students.find(); }
}

To use this class, first construct a class instance then call the .init() method.要使用这个类,首先构造一个类实例,然后调用.init()方法。

Generator Functions发电机功能

The following generator functions do not work:以下生成器功能不起作用:

// This code will fail
function* FindResults() {
yield db.students.findMany();
}

// This code will fail
function listEntries() { return db.students.findMany(); }
function* findResults() {
yield listEntries();
}

Use an async generator function instead:请改用async generator function

function listEntries() { return db.students.findMany(); }
async function* findResults() {
yield listEntries();
}

Array Sort数组排序

The following array sort does not work:以下数组排序不起作用:

// This code will fail
db.getCollectionNames().sort( ( collectionOne, collectionTwo ) => {
return db[ collectionOne ].estimatedDocumentCount() - db[ collectionOne ].estimatedDocumentCount() )
} );

Use .map() instead.请改用.map()

db.getCollectionNames().map( collectionName => {
return { collectionName, size: db[ collectionName ].estimatedDocumentCount() };
} ).sort( ( collectionOne, collectionTwo ) => {
return collectionOne.size - collectionTwo.size;
} ).map( collection => collection.collectionName);

This approach to array sort is often more performant than the equivalent unsupported code.这种数组排序方法通常比等效的不受支持的代码更具性能。