如何通过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()
method的帮助下显示集合中的所有文档。查询如下-
> 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" }
这是通过键名称从MongoDB检索值的查询,即我们已经考虑了键'CustomerCountryName'-
> db.retrieveValueFromAKeyDemo.find({},{"CustomerCountryName":1}).pretty();
以下是输出:
{ "_id" : ObjectId("5c9163b5a56efcc0f9e69048"), "CustomerCountryName" : "US" } { "_id" : ObjectId("5c9163c4a56efcc0f9e69049"), "CustomerCountryName" : "AUS" } { "_id" : ObjectId("5c9163d3a56efcc0f9e6904a"), "CustomerCountryName" : "UK" }