显示未定义和精确的 MongoDB 文档记录
mongodbdatabasebig data analytics更新于 2026/1/6 20:52:17
为此,请使用 forEach()。要显示值,请使用 printjson()。让我们创建一个包含文档的集合 −
> db.demo496.insertOne({"Name":"David","CountryName":"US"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b04ab0f3fa88e22790ce")
}
> db.demo496.insertOne({"Name":"John","CountryName":"AUS"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b054b0f3fa88e22790cf")
}
> db.demo496.insertOne({"Name":"Robert","CountryName":"UK"});{
"acknowledged" : true,
"insertedId" : ObjectId("5e84b05db0f3fa88e22790d0")
}
借助 find() 方法显示集合中的所有文档 −
> db.demo496.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e84b04ab0f3fa88e22790ce"), "Name" : "David", "CountryName" : "US" }
{ "_id" : ObjectId("5e84b054b0f3fa88e22790cf"), "Name" : "John", "CountryName" : "AUS" }
{ "_id" : ObjectId("5e84b05db0f3fa88e22790d0"), "Name" : "Robert", "CountryName" : "UK" }
以下是显示文档未定义的查询 −
> db.demo496.find({}).forEach( (done, notDone) => { printjson(notDone); });
这将产生以下输出 −
undefined undefined undefined
以下是使用.forEach()显示文档的查询 −
> db.demo496.find({}).forEach( (done, notDone) => { printjson(done); });
这将产生以下输出 −
{
"_id" : ObjectId("5e84b04ab0f3fa88e22790ce"),
"Name" : "David",
"CountryName" : "US"
}
{
"_id" : ObjectId("5e84b054b0f3fa88e22790cf"),
"Name" : "John",
"CountryName" : "AUS"
}
{
"_id" : ObjectId("5e84b05db0f3fa88e22790d0"),
"Name" : "Robert",
"CountryName" : "UK"
}

