匹配包含MongoDB中提供的数组的任意组合的数组字段?
将$nin运算符与$elemMatch和$not一起使用。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.combinationOfArrayDemo.insertOne({"StudentName":"Larry","StudentAge":21,"StudentFavouriteTechnicalSubject":["C","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f77cc8d10a061296a3c58") } > db.combinationOfArrayDemo.insertOne({"StudentName":"Mike","StudentAge":23,"StudentFavouriteTechnicalSubject":["C++","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f77dc8d10a061296a3c59") } > db.combinationOfArrayDemo.insertOne({"StudentName":"David","StudentAge":22,"StudentFavouriteTechnicalSubject":["Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5c7f77f48d10a061296a3c5a") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.combinationOfArrayDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c7f77cc8d10a061296a3c58"), "StudentName" : "Larry", "StudentAge" : 21, "StudentFavouriteTechnicalSubject" : [ "C", "Java" ] } { "_id" : ObjectId("5c7f77dc8d10a061296a3c59"), "StudentName" : "Mike", "StudentAge" : 23, "StudentFavouriteTechnicalSubject" : [ "C++", "Java" ] } { "_id" : ObjectId("5c7f77f48d10a061296a3c5a"), "StudentName" : "David", "StudentAge" : 22, "StudentFavouriteTechnicalSubject" : [ "Java" ] }
这是用于匹配包含MongoDB中提供的数组的任何组合的数组字段的查询-
> db.combinationOfArrayDemo.find({StudentFavouriteTechnicalSubject: {$not: {$elemMatch: {$nin: ['C++', 'Java']}}}}).pretty();
以下是输出-
{ "_id" : ObjectId("5c7f77dc8d10a061296a3c59"), "StudentName" : "Mike", "StudentAge" : 23, "StudentFavouriteTechnicalSubject" : [ "C++", "Java" ] } { "_id" : ObjectId("5c7f77f48d10a061296a3c5a"), "StudentName" : "David", "StudentAge" : 22, "StudentFavouriteTechnicalSubject" : [ "Java" ] }