如何在 MongoDB 中实现数组匹配?
对于数组匹配使用 $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++" ] }
广告