要从聚合中隐藏_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" }