迭代游标并打印 MongoDB 中的文档?
为此,使用 printjson。让我们首先创建一个带有文档的集合 −
> db.cursorDemo.insertOne({"StudentFullName":"John Smith","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f0d08f9e6ff3eb0ce442")
}
> db.cursorDemo.insertOne({"StudentFullName":"John Doe","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f0df8f9e6ff3eb0ce443")
}
> db.cursorDemo.insertOne({"StudentFullName":"Carol Taylor","StudentAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444")
}
> db.cursorDemo.insertOne({"StudentFullName":"Chris Brown","StudentAge":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cc7f0f88f9e6ff3eb0ce445")
}以下是使用 find() 方法从集合中显示所有文档的查询 −
> db.cursorDemo.find().pretty();
将产生以下输出 −
{
"_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
"StudentFullName" : "John Smith",
"StudentAge" : 23
}
{
"_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
"StudentFullName" : "John Doe",
"StudentAge" : 21
}
{
"_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
"StudentFullName" : "Carol Taylor",
"StudentAge" : 20
}
{
"_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
"StudentFullName" : "Chris Brown",
"StudentAge" : 24
}以下是使用 printjson 进行迭代和打印文档的查询 −
> db.cursorDemo.find().forEach(printjson);
将产生以下输出 −
{
"_id" : ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
"StudentFullName" : "John Smith",
"StudentAge" : 23
}
{
"_id" : ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
"StudentFullName" : "John Doe",
"StudentAge" : 21
}
{
"_id" : ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
"StudentFullName" : "Carol Taylor",
"StudentAge" : 20
}
{
"_id" : ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
"StudentFullName" : "Chris Brown",
"StudentAge" : 24
}以下查询供我们只想要特定字段(比如 "StudentFullName" 和 "StudentAge")时使用 −
> db.cursorDemo.find({}, { "StudentFullName": 1,"StudentAge":1, "_id": 0 }).forEach(printjson)将产生以下输出 −
{ "StudentFullName" : "John Smith", "StudentAge" : 23 }
{ "StudentFullName" : "John Doe", "StudentAge" : 21 }
{ "StudentFullName" : "Carol Taylor", "StudentAge" : 20 }
{ "StudentFullName" : "Chris Brown", "StudentAge" : 24 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP