如何对聚合隐藏 _id?
要对聚合隐藏 _id,请使用下面的语法:
db.yourCollectionName.aggregate( {$project : { _id : 0 , yourIncludeFieldName:1, yourIncludeFieldName:1 }} ).pretty();
为了解上述语法,让我们创建一个包含文档的集合。用于创建包含文档的集合的查询如下:
> db.hideidDemo.insertOne({"UserName":"Larry","UserAge":23,"UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c92b02336de59bd9de06392") } > db.hideidDemo.insertOne({"UserName":"Chris","UserAge":21,"UserCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c92b03036de59bd9de06393") } > db.hideidDemo.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c92b04036de59bd9de06394") }
借助 find() 方法显示某个集合中的所有文档。查询如下:
> db.hideidDemo.find().pretty();
以下是输出结果:
{ "_id" : ObjectId("5c92b02336de59bd9de06392"), "UserName" : "Larry", "UserAge" : 23, "UserCountryName" : "US" } { "_id" : ObjectId("5c92b03036de59bd9de06393"), "UserName" : "Chris", "UserAge" : 21, "UserCountryName" : "AUS" } { "_id" : ObjectId("5c92b04036de59bd9de06394"), "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "UK" }
以下是用于对聚合隐藏 _id 的查询:
> db.hideidDemo.aggregate( ... {$project : { ... _id : 0 , ... UserName:1, ... UserCountryName:1 ... }} ... ).pretty();
以下是输出结果:
{ "UserName" : "Larry", "UserCountryName" : "US" } { "UserName" : "Chris", "UserCountryName" : "AUS" } { "UserName" : "Robert", "UserCountryName" : "UK" }
广告