MongoDB中按多个条件查询嵌套数组
要查询嵌套数组,请在MongoDB中使用$elemMatch。让我们创建一个包含文档的集合-
> db.demo203.insertOne({ ... "_id" : "101", ... "Name" : "Chris", ... "details1" : [ ... { ... "empName" : "David", ... "salary" : "50000", ... "technology" : [ ... "MySQL", ... "MongoDB" ... ] ... }, ... { ... "empName" : "Carol", ... "salary" : "70000", ... ... "technology" : [ ... "Java", ... "Spring" ... ] ... } ... ] ...} ...); { "acknowledged" : true, "insertedId" : "101" }
在find()方法的帮助下显示集合中的所有文档-
> db.demo203.find();
这将产生以下输出-
{ "_id" : "101", "Name" : "Chris", "details1" : [ { "empName" : "David", "salary" : "50000", "technology" : [ "MySQL", "MongoDB" ] }, { "empName" : "Carol", "salary" : "70000", "technology" : [ "Java", "Spring" ] } ] }
这是通过多个条件查询嵌套数组的方法-
> db.demo203.find( ... {details1: { $elemMatch:{"technology" : "MySQL", "empName":"David"}}} ... ).pretty()
这将产生以下输出-
{ "_id" : "101", "Name" : "Chris", "details1" : [ { "empName" : "David", "salary" : "50000", "technology" : [ "MySQL", "MongoDB" ] }, { "empName" : "Carol", "salary" : "70000", "technology" : [ "Java", "Spring" ] } ] }