查询子字段的 MongoDB ?
您可以使用 dot(.) 符号按照子字段来查询。让我们创建一个拥有一个文档的集合。创建拥有一个文档的集合的查询如下 −
> db.queryBySubFieldDemo.insertOne( ... { ... "StudentPersonalDetails" : {"StudentName" : "John","StudentHobby" :"Photography"}, ... "StudentScores" : {"MathScore" : 56} ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c92c2995259fcd195499808") } > db.queryBySubFieldDemo.insertOne( ... { ... "StudentPersonalDetails" : {"StudentName" : "Chris","StudentHobby" :"Reading"}, ... "StudentScores" : {"MathScore" : 97} ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c92c2df5259fcd195499809") }
在 find() 方法的帮助下显示集合中的所有文档。查询如下 −
> db.queryBySubFieldDemo.find().pretty();
以下是输出 −
{ "_id" : ObjectId("5c92c2995259fcd195499808"), "StudentPersonalDetails" : { "StudentName" : "John", "StudentHobby" : "Photography" }, "StudentScores" : { "MathScore" : 56 } } { "_id" : ObjectId("5c92c2df5259fcd195499809"), "StudentPersonalDetails" : { "StudentName" : "Chris", "StudentHobby" : "Reading" }, "StudentScores" : { "MathScore" : 97 } }
以下是按照子字段的查询 −
> db.queryBySubFieldDemo.find({"StudentPersonalDetails.StudentName":"Chris"}).pretty();
以下是输出 −
{ "_id" : ObjectId("5c92c2df5259fcd195499809"), "StudentPersonalDetails" : { "StudentName" : "Chris", "StudentHobby" : "Reading" }, "StudentScores" : { "MathScore" : 97 } }
广告