查询 MongoDB 中深度嵌套的对象
要查询深度嵌套的对象,请在 MongoDB 中使用点(.)符号。让我们创建一个包含文档的集合 -
> 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 } ] } ] }
广告