如何使用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" } }