用 MongoDB 查询数组中的嵌套字段
要查询数组中的嵌套字段,请使用 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" } ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP