如何使用 MongoDB db.coll.find() 来根据内部类中的字段进行搜索?
使用点表示法 (.) 在内部类中进行 MongoDB 搜索。首先创建一个包含文档的集合 −
> db.searchInInnerDemo.insertOne( ... { ... "StudentFirstName" : "Robert", ... "StudentTechnicalDetails": ... { ... "StudentBackEndTechnology" : "MongoDB", ... "StudentLanguage" : "Java" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2dd89b64f4b851c3a13d2") } > > db.searchInInnerDemo.insertOne( ... { ... "StudentFirstName" : "David", ... "StudentTechnicalDetails": ... { ... "StudentBackEndTechnology" : "MySQL", ... "StudentLanguage" : "PHP" ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5cd2dda3b64f4b851c3a13d3") }
以下是使用 find() 方法显示集合中所有文档的查询 −
> db.searchInInnerDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd2dd89b64f4b851c3a13d2"), "StudentFirstName" : "Robert", "StudentTechnicalDetails" : { "StudentBackEndTechnology" : "MongoDB", "StudentLanguage" : "Java" } } { "_id" : ObjectId("5cd2dda3b64f4b851c3a13d3"), "StudentFirstName" : "David", "StudentTechnicalDetails" : { "StudentBackEndTechnology" : "MySQL", "StudentLanguage" : "PHP" } }
情况 1 − 在内部类中查询以仅匹配一个属性的查询 −
>db.searchInInnerDemo.find({"StudentTechnicalDetails.StudentBackEndTechnology":"MongoDB"}).pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd2dd89b64f4b851c3a13d2"), "StudentFirstName" : "Robert", "StudentTechnicalDetails" : { "StudentBackEndTechnology" : "MongoDB", "StudentLanguage" : "Java" } }
情况 2 − 使用全字段名扫描查询文档的查询 −
>db.searchInInnerDemo.find({"StudentTechnicalDetails":{"StudentBackEndTechnology":"MongoDB","StudentLanguage":"Java"}}).pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd2dd89b64f4b851c3a13d2"), "StudentFirstName" : "Robert", "StudentTechnicalDetails" : { "StudentBackEndTechnology" : "MongoDB", "StudentLanguage" : "Java" } }
广告