要查询深度嵌套的对象,请在MongoDB中使用dot(。)表示法。让我们创建一个包含文档的集合-
> db.demo350.insertOne( ... { ... id:101, ... Name: "Chris", ... details: [ ... { ... _id: 1, ... ClientNumber: "10001", ... ClientDetails: [ . ... { ... Name:"David", ... Age:29 ... }, ... { ... Name:"Bob", ... Age:31 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e553a68f8647eb59e5620b8") } > db.demo350.insertOne( ... { ... id:102, ... Name: "David", ... details: [ ... { ... _id: 2, ... ClientNumber: "10002", ... ClientDetails: [ ... { ... Name:"Carol", ... Age:42 ... }, ... { ... Name:"John", ... Age:37 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e553a8ff8647eb59e5620b9") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo350.find();
这将产生以下输出-
{ "_id" : ObjectId("5e553a68f8647eb59e5620b8"), "id" : 101, "Name" : "Chris", "details" : [ { "_id" : 1, "ClientNumber" : "10001", "ClientDetails" : [ { "Name" : "David", "Age" : 29 }, { "Name" : "Bob", "Age" : 31 } ] } ] } { "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }
以下是如何查询深度嵌套的对象-
> db.demo350.find({"details.ClientDetails.Name":"John"});
这将产生以下输出-
{ "_id" : ObjectId("5e553a8ff8647eb59e5620b9"), "id" : 102, "Name" : "David", "details" : [ { "_id" : 2, "ClientNumber" : "10002", "ClientDetails" : [ { "Name" : "Carol", "Age" : 42 }, { "Name" : "John", "Age" : 37 } ] } ] }