迭代游标并在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 }