MongoDB find() 函数是否能避免显示 _id?
是的,我们可以使用以下 MongoDB 语法来避免使用 _id −
db.yourCollectionName.find({},{ _id:0});
让我们首先创建一个带有文档的集合:>
> db.excludeIdDemo.insertOne({"CustomerName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7f62c1a844af18acdffb9") } > db.excludeIdDemo.insertOne({"CustomerName":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7f6311a844af18acdffba") } > db.excludeIdDemo.insertOne({"CustomerName":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7f6351a844af18acdffbb") } > db.excludeIdDemo.insertOne({"CustomerName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd7f6381a844af18acdffbc") }
以下是使用 find() 方法从集合中显示所有文档的查询 −
> db.excludeIdDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd7f62c1a844af18acdffb9"), "CustomerName" : "Larry" } { "_id" : ObjectId("5cd7f6311a844af18acdffba"), "CustomerName" : "Chris" } { "_id" : ObjectId("5cd7f6351a844af18acdffbb"), "CustomerName" : "Mike" } { "_id" : ObjectId("5cd7f6381a844af18acdffbc"), "CustomerName : "Bob" }
以下是 find() 中排除 _id 的查询 −
> db.excludeIdDemo.find({},{ _id:0});
这将产生以下输出 −
{ "CustomerName" : "Larry" } { "CustomerName" : "Chris" } { "CustomerName" : "Mike" } { "CustomerName" : "Bob" }
广告