要限制返回的数据,请使用find()
。字段的值0和1将决定什么字段值可见或隐藏。
让我们创建一个包含文档的集合-
> db.demo330.insertOne({"Id":101,"Name":"Chris","Age":21}); { "acknowledged" : true, "insertedId" : ObjectId("5e52149ff8647eb59e562081") } > db.demo330.insertOne({"Id":102,"Name":"Sam","Age":24}); { "acknowledged" : true, "insertedId" : ObjectId("5e5214aaf8647eb59e562082") } > db.demo330.insertOne({"Id":103,"Name":"David","Age":28}); { "acknowledged" : true, "insertedId" : ObjectId("5e5214b3f8647eb59e562083") } > db.demo330.insertOne({"Id":104,"Name":"Bob","Age":23}); . { "acknowledged" : true, "insertedId" : ObjectId("5e5214bdf8647eb59e562084") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo330.find();
这将产生以下输出-
{ "_id" : ObjectId("5e52149ff8647eb59e562081"), "Id" : 101, "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e5214aaf8647eb59e562082"), "Id" : 102, "Name" : "Sam", "Age" : 24 } { "_id" : ObjectId("5e5214b3f8647eb59e562083"), "Id" : 103, "Name" : "David", "Age" : 28 } { "_id" : ObjectId("5e5214bdf8647eb59e562084"), "Id" : 104, "Name" : "Bob", "Age" : 23 }
以下是限制MongoDB中返回数据的查询。由于设置了1,因此只有字段“名称”可见-
> db.demo330.find({},{Name:1});
这将产生以下输出-
{ "_id" : ObjectId("5e52149ff8647eb59e562081"), "Name" : "Chris" } { "_id" : ObjectId("5e5214aaf8647eb59e562082"), "Name" : "Sam" } { "_id" : ObjectId("5e5214b3f8647eb59e562083"), "Name" : "David" } { "_id" : ObjectId("5e5214bdf8647eb59e562084"), "Name" : "Bob" }