按照以下语法,将不想包含的字段设置为0。在这里,我们将字段“ yourFieldName1”和“ yourFieldName2”设置为0-
db.yourCollectionName.find(yourQuery, {yourFieldName1:0,yourFieldName2:0});
为了理解上述语法,让我们创建一个包含文档的集合-
> db.demo567.insertOne({"Name":"Chris",Age:21});{ "acknowledged" : true, "insertedId" : ObjectId("5e908fa139cfeaaf0b97b57b") } > db.demo567.insertOne({"Name":"David",Age:23});{ "acknowledged" : true, "insertedId" : ObjectId("5e908fa939cfeaaf0b97b57c") } > db.demo567.insertOne({"Name":"Bob",Age:22});{ "acknowledged" : true, "insertedId" : ObjectId("5e908faf39cfeaaf0b97b57d") } > db.demo567.insertOne({"Name":"Carol",Age:20});{ "acknowledged" : true, "insertedId" : ObjectId("5e908fb539cfeaaf0b97b57e") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo567.find();
这将产生以下输出-
{ "_id" : ObjectId("5e908fa139cfeaaf0b97b57b"), "Name" : "Chris", "Age" : 21 } { "_id" : ObjectId("5e908fa939cfeaaf0b97b57c"), "Name" : "David", "Age" : 23 } { "_id" : ObjectId("5e908faf39cfeaaf0b97b57d"), "Name" : "Bob", "Age" : 22 } { "_id" : ObjectId("5e908fb539cfeaaf0b97b57e"), "Name" : "Carol", "Age" : 20 }
以下是查询以排除find()
-中的某些字段
> db.demo567.find({Name:{$in:["Chris","Bob"]}}, {Age:0,_id:0});
这将产生以下输出-
{ "Name" : "Chris" } { "Name" : "Bob" }