为此,只需在 MongoDB 中使用点表示法和 find() 即可。让我们创建一个包含文档的集合 -
> db.demo465.insertOne( ... { ... id: 101, ... details: [{ ... Name: "Chris", ... Info: { ... Subject: "MongoDB", ... Marks:67 ... } ... }, { ... Name: "David", ... Info: { ... Subject: "MySQL", ... Marks:78 ... } ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e80421bb0f3fa88e2279061") } > > db.demo465.insertOne( ... { ... id: 102, ... details: [{ ... Name: "Bob", ... Info: { ... Subject: "Java", ... Marks:45 ... } ... }, { ... Name: "Carol", ... Info: { ... Subject: "C", ... Marks:67 ... } ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e80421cb0f3fa88e2279062") }
借助 find() 方法显示集合中的所有文档 -
> db.demo465.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e80421bb0f3fa88e2279061"), "id" : 101, "details" : [ { "Name" : "Chris", "Info" : { "Subject" : "MongoDB", "Marks" : 67 } }, { "Name" : "David", "Info" : { "Subject" : "MySQL", "Marks" : 78 } } ] } { "_id" : ObjectId("5e80421cb0f3fa88e2279062"), "id" : 102, "details" : [ { "Name" : "Bob", "Info" : { "Subject" : "Java", "Marks" : 45 } }, { "Name" : "Carol", "Info" : { "Subject" : "C", "Marks" : 67 } } ] }
以下是获取数组中包含另一个文档的所有文档的查询 -
> db.demo465.find({"details.Name":"Bob"});
这将产生以下输出 -
{ "_id" : ObjectId("5e80421cb0f3fa88e2279062"), "id" : 102, "details" : [ { "Name" : "Bob", "Info" : { "Subject" : "Java", "Marks" : 45 } }, { "Name" : "Carol", "Info" : { "Subject" : "C", "Marks" : 67 } } ] }
以上是如何使用 MongoDB 获取数组中包含另一个文档的所有文档?的详细内容。更多信息请关注PHP中文网其他相关文章!