要查询数组中的嵌套字段,请在MongoDB中使用$elemMatch。让我们创建一个包含文档的集合-
> db.demo153.insertOne({"ClientDetails":[{"ClientName":"Chris","ClientProject":"Online Banking System"},{"ClientName":"David","ClientProject":"Online School Management"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e351957fdf09dd6d08539df") } > db.demo153.insertOne({"ClientDetails":[{"ClientName":"Carol","ClientProject":"Online Book System"},{"ClientName":"Mike","ClientProject":"Game Development"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e3519c9fdf09dd6d08539e0") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo153.find();
这将产生以下输出-
{ "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientProject" : "Online Banking System" }, { "ClientName" : "David", "ClientProject" : "Online School Management" } ] } { "_id" : ObjectId("5e3519c9fdf09dd6d08539e0"), "ClientDetails" : [ { "ClientName" : "Carol", "ClientProject" : "Online Book System" }, { "ClientName" : "Mike", "ClientProject" : "Game Development" } ] }
以下是如何查询数组内的嵌套字段-
> db.demo153.find({"ClientDetails": { "$elemMatch" : {"ClientProject": { "$in": ["Online Banking System"] } } } });
这将产生以下输出-
{ "_id" : ObjectId("5e351957fdf09dd6d08539df"), "ClientDetails" : [ { "ClientName" : "Chris", "ClientProject" : "Online Banking System" }, { "ClientName" : "David", "ClientProject" : "Online School Management" } ] }