使用 find() 在 MongoDB 中搜索嵌套键?
要使用 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" } }
广告