如何在 MongoDB 中获取包含数组中另一文档的所有文档?
为此,只需在 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 } } ] }
广告