查詢子欄位的 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 } }
廣告