使用$all进行数组匹配。$all运算符选择字段值是包含所有指定元素的数组的文档。让我们用文档创建一个集合-
> db.demo668.createIndex({"ListOfSubject":1}); { "createdCollectionAutomatically" : true, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 } > db.demo668.insert({"ListOfSubject":["MySQL","Java","C"]}); WriteResult({ "nInserted" : 1 }) > db.demo668.insert({"ListOfSubject":["MongoDB","Python","C++"]}); WriteResult({ "nInserted" : 1 }) > db.demo668.insert({"ListOfSubject":["C#","Spring","Hibernate","MongoDB"]}); WriteResult({ "nInserted" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo668.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea311df04263e90dac943d6"), "ListOfSubject" : [ "MySQL", "Java", "C" ] } { "_id" : ObjectId("5ea311e004263e90dac943d7"), "ListOfSubject" : [ "MongoDB", "Python", "C++" ] } { "_id" : ObjectId("5ea311e104263e90dac943d8"), "ListOfSubject" : [ "C#", "Spring", "Hibernate", "MongoDB" ] }
以下是数组匹配的查询-
> db.demo668.find({"ListOfSubject":{ $all:["MongoDB","C++"]}});
这将产生以下输出-
{ "_id" : ObjectId("5ea311e004263e90dac943d7"), "ListOfSubject" : [ "MongoDB", "Python", "C++" ] }