使用 mongosh 进行查询时,首先要连接到一个 MongoDB 服务器。连接成功后,就可以使用 use
命令选择要操作的数据库,然后就可以使用 MongoDB 的查询语句来执行查询了。
例如,下面的例子展示了如何使用 mongosh 连接到一个 MongoDB 服务器,然后使用 use
命令选择数据库 test
,最后使用 db.customers.find()
命令查询 customers 集合中的所有文档:
$ mongosh
> mongodb://127.0.0.1:27017
> use test
switched to db test
> db.customers.find()
{ "_id" : ObjectId("5e9d74dc7b9e935aadcf16ad"), "name" : "Alice", "age" : 25 }
{ "_id" : ObjectId("5e9d74dc7b9e935aadcf16ae"), "name" : "Bob", "age" : 30 }
{ "_id" : ObjectId("5e9d74dc7b9e935aadcf16af"), "name" : "Charlie", "age" : 35 }
...
注意:在上面的例子中,use
命令是用来选择要操作的数据库的,而 db
命令是用来获取当前数据库的句柄的,所以 db.customers.find()
中的 db
就是当前数据库的句柄。
除了 find()
以外,mongosh 还支持其他的 MongoDB 查询语句,例如 findOne()
、count()
等。可以在 mongosh 中使用 db.help()
命令查看所有可用的查询语句的详细信息。