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 除了这里列出的替代方案外,您还可以使用mongocompat代码段访问遗留的mongo shell APIs. 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方法。相反,请使用“替代资源”列中列出的方法。
db.collection.copyTo() | $out |
db.collection.count() | |
db.collection.insert() | |
db.collection.remove() | |
db.collection.save() | |
db.collection.update() | |
DBQuery.shellBatchSize | |
Mongo.getSecondaryOk | Mongo.getReadPrefMode() |
Mongo.isCausalConsistency | Session.getOptions() |
Mongo.setSecondaryOk | Mongo.setReadPref() |
rs.secondaryOk |
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 shell直接连接到secondary副本集成员时,必须运行mongo.setReadPref() to enable secondary reads.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:要指定读取首选项,您可以使用以下任一方法:
The连接到节点时的readPreferenceconnection string option when connecting to the node.readPreference连接字符串选项。TheMongo.setReadPref()method.Mongo.setReadPref()方法。
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副本集成员时,如果读取首选项设置为primaryPreferred、secondary或secondaryPreferred,则不需要运行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 dbsshow databasesshow collectionsshow 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中不同。
mongo | mongosh | |
|---|---|---|
ObjectId.str | 6419ccfce40afaf9317567b7 | Undefined (Not available) |
ObjectId.valueOf() | ObjectId.str:ObjectId.str的值:6419ccfce40afaf9317567b7 | ObjectId("6419ccfce40afaf9317567b7") |
ObjectId.toString() | ObjectId("6419ccfce40afaf9317567b7") | 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 MongoDB Shell继续支持mongo shell. However, the preferred types have been updated to better align with the MongoDB drivers. 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 MongoDB Shell中数值变量的首选类型与传统mongo shell. The types in mongosh better align with the types used by the MongoDB Drivers.mongo Shell中建议的类型不同。mongosh中的类型更好地与MongoDB驱动程序使用的类型对齐。
mongo type | mongosh type |
|---|---|
NumberInt | Int32 |
NumberLong | Long |
NumberDecimal | Decimal128 |
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.js,mongosh不会加载遗留的.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()方法中访问脚本的文件名或目录。
Retryable Writes可重试写入
By default, retryable writes are:默认情况下,可重试的写入操作包括:
- enabled in
mongosh disabled in the legacy在遗留的mongoshellmongo壳中被禁用
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.有关详细信息,请参阅获取代码段的帮助。