如何仅在 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 }
广告