Docs Home / mongosh / Reference

Compatibility Changes with Legacy mongo Shell与旧版mongo Shell的兼容性更改

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

snippet install mongocompat

Deprecated Methods弃用的方法

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

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.不再需要。请参见secondary节点上的读取操作

Read Preference Behavior读取偏好行为

Read Operations on a Secondary Nodesecondary节点上的读取操作

When using the legacy mongo shell to connect directly to secondary replica set member, you must run mongo.setReadPref() to enable secondary reads.当使用传统mongo shell直接连接到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助手方法始终使用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. Retryable writes were disabled by default in the legacy mongo shell. To disable retryable writes, use --retryWrites=false.mongosh中默认启用可重试写入。默认情况下,旧版mongo shell中禁用了可重试写入。要禁用可重试写入,请使用--retryWrites=false

ObjectId Methods and AttributesObjectId方法和属性

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

Method or Attribute方法或属性mongo Behavior行为mongosh 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. In mongosh numbers are stored as 32 bit integers, Int32, or else as Double if the value cannot be stored as an Int32.传统的mongo shell默认将数值存储为double。在mongosh中,数字存储为32位整数Int32,如果值不能存储为Int32,则存储为Double

MongoDB Shell continues to support the numeric types that are supported in mongo shell. However, the preferred types have been updated to better align with the MongoDB drivers. MongoDB Shell继续支持mongo Shell中支持的数字类型。但是,首选类型已经更新,以便更好地与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. The types in mongosh better align with the types used by the MongoDB Drivers.MongoDB Shell中数值变量的首选类型与传统mongo Shell中建议的类型不同。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和遗留mongo shell连接到同一集合,则数据类型可能会存储不一致。

Tip

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

Undefined Values

The undefined BSON type is deprecated. 不推荐使用undefinedBSON类型。If you try to insert a document with the undefined JS type in mongosh, your deployment replaces the undefined value in your document with the BSON null value. 如果你试图在mongosh中插入一个具有未定义JS类型的文档,你的部署会用BSON空值替换文档中的未定义值。There is no supported way of inserting undefined values into your database using mongosh.不支持使用mongosh将未定义的值插入数据库。

For example, consider running the following code to insert a document in mongosh:例如,考虑运行以下代码以在mongosh中插入文档:

db.people.insertOne( { name : "Sally", age : undefined } )

When you run this code in mongosh, the shell inserts the following document:mongosh中运行此代码时,shell会插入以下文档:

{ name : "Sally", age : null }

mongosh represents any BSON undefined values stored using other tools, such as the Go Driver or the legacy mongo shell, as null.mongosh将使用其他工具(如Go Driver或遗留mongo shell)存储的任何BSON未定义值表示为null

Object Quoting Behavior对象引用行为

mongosh does not quote object keys in its output, and places single quotes on values. 在输出中不引用对象键,并在值上放置单引号。To reproduce the output of the legacy mongo shell, which wraps both the keys and string values in double quotes, use mongosh --eval with EJSON.stringify().要再现遗留mongo shell的输出,该shell将键和字符串值都封装在双引号中,请使用mongosh -eval配合EJSON.stringify()

For example, the following command returns the items in the sales collection on the test database with double quotes and indentation:例如,以下命令使用双引号和缩进返回test数据库上sales集合中的项目:

mongosh --eval "EJSON.stringify(db.sales.findOne().toArray(), null, 2)"

The output looks like the following:输出如下:

{
"_id": {
"$oid": "64da90c1175f5091debcab26"
},
"custId": 345,
"purchaseDate": {
"$date": "2023-07-04T00:00:00Z"
},
"quantity": 4,
"cost": {
"$numberDecimal": "100.60"
}
}

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()的回调
  • JavaScript setters in classes类中的JavaScript设置程序

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.findOne();
}

// This code will fail此代码将失败
function listEntries() { return db.students.findOne(); }
function* findResults() {
yield listEntries();
}

Use an async generator function instead:请改用异步生成器函数:

function listEntries() { return db.students.findOne(); }
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.这种数组排序方法通常比等效的不受支持的代码性能更高。

JavaScript SettersJavaScript设置器

The following JavaScript setter does not work:以下JavaScript设置程序不起作用:

// This code will fail此代码将失败
class TestClass {
value = 1;

get property() {
return this.value;
}

// does not work:不起作用:
set property(value) {
this.value = db.test.findOne({ value });
}
}

Command Exceptions命令例外

For commands whose output includes { ok: 0 }, mongosh returns a consistent exception and omits the server raw output. The legacy mongo shell returns output that varies for each command.对于输出包含{ ok: 0 }的命令,mongosh返回一致的异常并省略服务器原始输出。传统的mongo shell返回的输出因每个命令而异。

For details, see Run Commands.有关详细信息,请参阅运行命令

Shell ConfigurationShell配置

The legacy mongo shell uses a configuration file named .mongorc.js.传统的mongoshell使用一个名为.mongorc.js的配置文件。

If mongosh finds .mongorc.js on startup but doesn't find .mongoshrc.js, mongosh doesn't load the legacy .mongorc.js file and states you should rename .mongorc.js to .mongoshrc.js.如果mongosh在启动时找到.mongorc.js,但找不到.mongorc.jsmongosh不会加载遗留的.mongorc.js文件,并建议您将.mongorc.js重命名为.mongoshrc.js

For details, see .mongoshrc Configuration File.有关详细信息,请参阅.mongoshrc配置文件

Data Types数据类型

MongoDB stores data using BSON, which supports additional data types that aren't available in JSON. MongoDB使用BSON存储数据,BSON支持JSON中不可用的其他数据类型。The mongosh shell has better data type support for drivers than the legacy mongo shell.mongosh shell对驱动程序的数据类型支持比传统mongoshell更好。

For details, see Data Types.有关详细信息,请参阅数据类型

Methods方法

The legacy mongo shell cannot access a script's file name or directory in the load() method.旧版mongo shell无法在load()方法中访问脚本的文件名或目录。

For details, see load().有关详细信息,请参阅load()

Retryable Writes可重试写入

By default, retryable writes are:默认情况下,可重试的写入操作包括:

  • enabled in mongosh
  • disabled in the legacy mongo shell在遗留的mongo壳中被禁用

To disable retryable writes, use --retryWrites=false.要禁用可重试写入,请使用--retryWrites=false

For details, see --retryWrites.有关详细信息,请参阅--retryWrites

Legacy Output传统输出

The mongosh shell returns output that differs from the legacy mongo shell. mongosh shell返回的输出与传统mongo shell不同。If you have scripts that require the output to be formatted in a similar way to the legacy mongo shell, try reformatting the mongosh output with EJSON.stringify().如果脚本要求输出以与传统mongo shell类似的方式格式化,请尝试使用EJSONstringify()重新格式化mongosh输出。

For details, see Legacy tojsononeline().有关详细信息,请参阅遗留的tojsonoline()

Code Snippets代码片段

Working with code snippets is different for the legacy mongo shell.对于传统的mongo shell,使用代码片段是不同的。

For details, see Get Help for a Snippet.有关详细信息,请参阅获取代码段的帮助