要从MongoDB结果中删除_id,您需要将_id字段设置为0。以下是语法
db.yourCollectionName.find({},{_id:0});
为了理解它,让我们创建一个包含文档的集合。以下是查询
> db.removeIdDemo.insertOne({"UserName":"John","UserAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c9bb4042d66697741252440") } > db.removeIdDemo.insertOne({"UserName":"Mike","UserAge":27}); { "acknowledged" : true, "insertedId" : ObjectId("5c9bb40c2d66697741252441") } > db.removeIdDemo.insertOne({"UserName":"Sam","UserAge":34}); { "acknowledged" : true, "insertedId" : ObjectId("5c9bb4162d66697741252442") } > db.removeIdDemo.insertOne({"UserName":"Carol","UserAge":29}); { "acknowledged" : true, "insertedId" : ObjectId("5c9bb4222d66697741252443") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.removeIdDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c9bb4042d66697741252440"), "UserName" : "John", "UserAge" : 23 } { "_id" : ObjectId("5c9bb40c2d66697741252441"), "UserName" : "Mike", "UserAge" : 27 } { "_id" : ObjectId("5c9bb4162d66697741252442"), "UserName" : "Sam", "UserAge" : 34 } { "_id" : ObjectId("5c9bb4222d66697741252443"), "UserName" : "Carol", "UserAge" : 29 }
以下是从Mongo结果中删除_id的查询
> db.removeIdDemo.find({},{_id:0});
这将产生以下输出
{ "UserName" : "John", "UserAge" : 23 } { "UserName" : "Mike", "UserAge" : 27 } { "UserName" : "Sam", "UserAge" : 34 } { "UserName" : "Carol", "UserAge" : 29 }