要find()
在MongoDB中搜索嵌套键,可以使用点(。)表示法。以下是语法
db.yourCollectionName.find({"yourOuterFieldName.yourInnerFieldName":"yourValue"}).pretty();
让我们首先创建一个包含文档的集合:
>db.searchForNestedKeysDemo.insertOne({"ClientName":"Larry","ClientAge":28,"ClientExtra Details":{"isEducated":true,"CountryName":"US"}}); { "acknowledged" : true, "insertedId" : ObjectId("5ca20e8b66324ffac2a7dc64") } >db.searchForNestedKeysDemo.insertOne({"ClientName":"Chris","ClientAge":29,"ClientExtra Details":{"isEducated":false,"CountryName":"UK"}}); { "acknowledged" : true, "insertedId" : ObjectId("5ca20ea366324ffac2a7dc65") } >db.searchForNestedKeysDemo.insertOne({"ClientName":"David","ClientAge":39,"ClientExtra Details":{"isEducated":true,"CountryName":"AUS"}}); { "acknowledged" : true, "insertedId" : ObjectId("5ca20eba66324ffac2a7dc66") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.searchForNestedKeysDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca20e8b66324ffac2a7dc64"), "ClientName" : "Larry", "ClientAge" : 28, "ClientExtraDetails" : { "isEducated" : true, "CountryName" : "US" } } { "_id" : ObjectId("5ca20ea366324ffac2a7dc65"), "ClientName" : "Chris", "ClientAge" : 29, "ClientExtraDetails" : { "isEducated" : false, "CountryName" : "UK" } } { "_id" : ObjectId("5ca20eba66324ffac2a7dc66"), "ClientName" : "David", "ClientAge" : 39, "ClientExtraDetails" : { "isEducated" : true, "CountryName" : "AUS" } }
以下是在MongoDB中搜索嵌套键的查询
> db.searchForNestedKeysDemo.find({"ClientExtraDetails.CountryName":"UK"}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca20ea366324ffac2a7dc65"), "ClientName" : "Chris", "ClientAge" : 29, "ClientExtraDetails" : { "isEducated" : false, "CountryName" : "UK" } }