如何在 MongoDB 中获取游标的值?


若要在 MongoDB 中获取游标的值,请使用 hasNext()。让我们使用文档创建一个集合 -

> db.demo191.insertOne({"EmployeeId":1,"EmployeeName":"Chris Brown"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ad95303d395bdc21346c5")
}
> db.demo191.insertOne({"EmployeeId":2,"EmployeeName":"David Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ad95f03d395bdc21346c6")
}
> db.demo191.insertOne({"EmployeeId":1,"EmployeeName":"John Doe"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ad96803d395bdc21346c7")
}
> db.demo191.insertOne({"EmployeeId":1,"EmployeeName":"John Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3ad97003d395bdc21346c8")
}

使用 find() 方法显示集合中的所有文档 -

> db.demo191.find();

这将产生以下输出 -

{ "_id" : ObjectId("5e3ad95303d395bdc21346c5"), "EmployeeId" : 1, "EmployeeName" : "Chris Brown" }
{ "_id" : ObjectId("5e3ad95f03d395bdc21346c6"), "EmployeeId" : 2, "EmployeeName" : "David Miller" }
{ "_id" : ObjectId("5e3ad96803d395bdc21346c7"), "EmployeeId" : 1, "EmployeeName" : "John Doe" }
{ "_id" : ObjectId("5e3ad97003d395bdc21346c8"), "EmployeeId" : 1, "EmployeeName" : "John Smith" }

以下是获取游标对象的值的查询 -

> var cursor = db.demo191.find( { "EmployeeId":1 } );
> while (cursor.hasNext()) {
...   print(tojson(cursor.next()));
...}

这将产生以下输出 -

{
   "_id" : ObjectId("5e3ad95303d395bdc21346c5"),
   "EmployeeId" : 1,
   "EmployeeName" : "Chris Brown"
}
{
   "_id" : ObjectId("5e3ad96803d395bdc21346c7"),
   "EmployeeId" : 1,
   "EmployeeName" : "John Doe"
}
{
   "_id" : ObjectId("5e3ad97003d395bdc21346c8"),
   "EmployeeId" : 1,
   "EmployeeName" : "John Smith"
}

更新于: 27-Mar-2020

587 次浏览

开始你的职业生涯

通过完成课程获得认证

开始
广告