用於巢狀文件的 MongoDB find() 查詢?
如要從巢狀文件中獲取值,請使用點符號。讓我們使用文件建立集合 −
> db.demo591.insert([ ... { "Name": "John", "Age": 23 }, ... {"Name": "Carol", "Age": 26}, ... { "Name": "Robert", "Age": 29, ... details:[ ... { ... Email:"Robert@gmail.com",CountryName:"US"},{"Post":35} ... ]} ... ]); BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
使用 find() 方法顯示集合中的所有文件 −
> db.demo591.find();
這將生成以下輸出 −
{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd3"), "Name" : "John", "Age" : 23 } { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd4"), "Name" : "Carol", "Age" : 26 } { "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [ { "Email" : "Robert@gmail.com", "CountryName" : "US" }, { "Post" : 35 } ] }
以下是使用點符號獲取巢狀文件的查詢 −
> db.demo591.find({"details.Email": "Robert@gmail.com"});
這將生成以下輸出 −
{ "_id" : ObjectId("5e92dd08fd2d90c177b5bcd5"), "Name" : "Robert", "Age" : 29, "details" : [ { "Email" : "Robert@gmail.com", "CountryName" : "US" }, { "Post" : 35 } ] }
廣告