您可以使用点(。)表示法按子字段进行查询。让我们用文档创建一个集合。使用文档创建集合的查询如下-
> 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()
method的帮助下显示集合中的所有文档。查询如下-
> 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 } }