如何在MongoDB中仅返回单个属性“ _id”?
以下是在MongoDB中仅返回单个属性_id的语法
db.yourCollectionName.find({}, {"_id": 1}).pretty();
首先让我们创建一个包含文档的集合
> db.singlePropertyIdDemo.insertOne({"_id":101,"UserName":"Larry","UserAge":21}); { "acknowledged" : true, "insertedId" : 101 } > db.singlePropertyIdDemo.insertOne({"_id":102,"UserName":"Mike","UserAge":26}); { "acknowledged" : true, "insertedId" : 102 } > db.singlePropertyIdDemo.insertOne({"_id":103,"UserName":"Chris","UserAge":24}); { "acknowledged" : true, "insertedId" : 103 } > db.singlePropertyIdDemo.insertOne({"_id":104,"UserName":"Robert","UserAge":23}); { "acknowledged" : true, "insertedId" : 104 } > db.singlePropertyIdDemo.insertOne({"_id":105,"UserName":"John","UserAge":27}); { "acknowledged" : true, "insertedId" : 105 }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.singlePropertyIdDemo.find().pretty();
这将产生以下输出
{ "_id" : 101, "UserName" : "Larry", "UserAge" : 21 } { "_id" : 102, "UserName" : "Mike", "UserAge" : 26 } { "_id" : 103, "UserName" : "Chris", "UserAge" : 24 } { "_id" : 104, "UserName" : "Robert", "UserAge" : 23 } { "_id" : 105, "UserName" : "John", "UserAge" : 27 }
以下是仅返回单个属性_id的查询
> db.singlePropertyIdDemo.find({}, {"_id": 1}).pretty();
这将产生以下输出
{ "_id" : 101 } { "_id" : 102 } { "_id" : 103 } { "_id" : 104 } { "_id" : 105 }