To restrict returned data, use find(). The values 0 and 1 for fields would decide what all field values would be visible or hidden.
Let us create a collection with documents −
> 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")
}Display all documents from a collection with the help of find() method −
> db.demo330.find();
This will produce the following output −
{ "_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 }Following is the query to restrict returned data in MongoDB. Only field “Name” would be visible since 1 is set −
> db.demo330.find({},{Name:1});This will produce the following output −
{ "_id" : ObjectId("5e52149ff8647eb59e562081"), "Name" : "Chris" }
{ "_id" : ObjectId("5e5214aaf8647eb59e562082"), "Name" : "Sam" }
{ "_id" : ObjectId("5e5214b3f8647eb59e562083"), "Name" : "David" }
{ "_id" : ObjectId("5e5214bdf8647eb59e562084"), "Name" : "Bob" }