首先让我们创建一个包含文档的集合-
> db.excludeIdDemo.insertOne({"StudentFirstName":"John","StudentAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5cd701a56d78f205348bc632") } > db.excludeIdDemo.insertOne({"StudentFirstName":"Robert","StudentAge":20}); { "acknowledged" : true, "insertedId" : ObjectId("5cd701af6d78f205348bc633") } > db.excludeIdDemo.insertOne({"StudentFirstName":"Chris","StudentAge":24}); { "acknowledged" : true, "insertedId" : ObjectId("5cd701b86d78f205348bc634") }
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.excludeIdDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5cd701a56d78f205348bc632"), "StudentFirstName" : "John", "StudentAge" : 21 } { "_id" : ObjectId("5cd701af6d78f205348bc633"), "StudentFirstName" : "Robert", "StudentAge" : 20 } { "_id" : ObjectId("5cd701b86d78f205348bc634"), "StudentFirstName" : "Chris", "StudentAge" : 24 }
以下是使用聚合框架排除_id而不包含其他字段的查询-
> db.excludeIdDemo.aggregate( { $project : { _id : 0, "StudentFirstName": 1 } } );
这将产生以下输出-
{ "StudentFirstName" : "John" } { "StudentFirstName" : "Robert" } { "StudentFirstName" : "Chris" }