如何通过键名从 MongoDB 检索值?
要通过键名从 MongoDB 中检索值,请使用以下语法 −
db.yourCollectionName.find({},{"yourFieldName":1}).pretty();
为了理解上述语法,让我们创建一个带有文档的集合。创建带有文档的集合的查询如下 −
> db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Larry","CustomerAge":21,"CustomerCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9163b5a56efcc0f9e69048") } > db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Chris","CustomerAge":24,"CustomerCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9163c4a56efcc0f9e69049") } > db.retrieveValueFromAKeyDemo.insertOne({"CustomerName":"Mike","CustomerAge":26,"CustomerCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9163d3a56efcc0f9e6904a") }
使用 find() 方法显示集合中的所有文档。查询如下 −
> db.retrieveValueFromAKeyDemo.find().pretty();
以下是输出 −
{ "_id" : ObjectId("5c9163b5a56efcc0f9e69048"), "CustomerName" : "Larry", "CustomerAge" : 21, "CustomerCountryName" : "US" } { "_id" : ObjectId("5c9163c4a56efcc0f9e69049"), "CustomerName" : "Chris", "CustomerAge" : 24, "CustomerCountryName" : "AUS" } { "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"), "CustomerName" : "Mike", "CustomerAge" : 26, "CustomerCountryName" : "UK" }
以下是通过键名(即我们已经考虑了键 CustomerCountryName)从 MongoDB 中检索值的查询 −
> db.retrieveValueFromAKeyDemo.find({},{"CustomerCountryName":1}).pretty();
以下是输出
{ "_id" : ObjectId("5c9163b5a56efcc0f9e69048"), "CustomerCountryName" : "US" } { "_id" : ObjectId("5c9163c4a56efcc0f9e69049"), "CustomerCountryName" : "AUS" } { "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"), "CustomerCountryName" : "UK" }
广告