查询MongoDB中的数组数组?
使用$in运算符查询MongoDB中的数组数组。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.arrayOfArraysDemo.insertOne({"EmployeeName":"Larry","EmployeeSkills":[["Java","MongoDB","MySQL","SQL Server"]]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f7a8d8d10a061296a3c5b") } > db.arrayOfArraysDemo.insertOne({"EmployeeName":"Mike","EmployeeSkills":[["C","C++"]]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f7aa68d10a061296a3c5c") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.arrayOfArraysDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c7f7a8d8d10a061296a3c5b"), "EmployeeName" : "Larry", "EmployeeSkills" : [ [ "Java", "MongoDB", "MySQL", "SQL Server" ] ] } { "_id" : ObjectId("5c7f7aa68d10a061296a3c5c"), "EmployeeName" : "Mike", "EmployeeSkills" : [ [ "C", "C++" ] ] }
这是查询MongoDB中的数组数组的查询-
> db.arrayOfArraysDemo.find({'EmployeeSkills':{$elemMatch:{$elemMatch:{$in:['MongoDB']}}} }).pretty();
以下是输出-
{ "_id" : ObjectId("5c7f7a8d8d10a061296a3c5b"), "EmployeeName" : "Larry", "EmployeeSkills" : [ [ "Java", "MongoDB", "MySQL", "SQL Server" ] ] }