为此,只需使用find()
。将您不想选择的字段设置为0。让我们创建一个包含文档的集合-
> db.demo269.insertOne({StudentId:101,StudentSubject:"MySQL"}); { "acknowledged" : true, "insertedId" : ObjectId("5e481caa1627c0c63e7dbab4") } > db.demo269.insertOne({StudentId:102,StudentSubject:"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5e481cb11627c0c63e7dbab5") } > db.demo269.insertOne({StudentId:103,StudentSubject:"MongoDB"}); { "acknowledged" : true, "insertedId" : ObjectId("5e481cb21627c0c63e7dbab6") } > db.demo269.insertOne({StudentId:104,StudentSubject:"C"}); { "acknowledged" : true, "insertedId" : ObjectId("5e481cb21627c0c63e7dbab7") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo269.find();
这将产生以下输出-
{ "_id" : ObjectId("5e481caa1627c0c63e7dbab4"), "StudentId" : 101, "StudentSubject" : "MySQL" } { "_id" : ObjectId("5e481cb11627c0c63e7dbab5"), "StudentId" : 102, "StudentSubject" : "Java" } { "_id" : ObjectId("5e481cb21627c0c63e7dbab6"), "StudentId" : 103, "StudentSubject" : "MongoDB" } { "_id" : ObjectId("5e481cb21627c0c63e7dbab7"), "StudentId" : 104, "StudentSubject" : "C" }
以下是仅选择特定字段而不是全部的查询-
> db.demo269.find({},{"StudentId":0,_id:0});
这将产生以下输出-
{ "StudentSubject" : "MySQL" } { "StudentSubject" : "Java" } { "StudentSubject" : "MongoDB" } { "StudentSubject" : "C" }