您可以为此使用$nin运算符。为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.documentWithAParticularFieldValueDemo.insertOne( ... { ... ... "StudentId" : 101, ... "StudentDetails" : ... [ ... { ... "TheoryMarks": 78, ... "PracticalMarks": 91 ... }, ... { ... "TheoryMarks": 75, ... "PracticalMarks": 75 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c8edab72f684a30fbdfd586") } > db.documentWithAParticularFieldValueDemo.insertOne( ... ... { "StudentId" : 102, ... "StudentDetails" : [ ... { ... "TheoryMarks": 91, ... "PracticalMarks": 91 ... }, ... { ... "TheoryMarks": 75, ... "PracticalMarks": 75 ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c8edaf12f684a30fbdfd587") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.documentWithAParticularFieldValueDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8edab72f684a30fbdfd586"), "StudentId" : 101, "StudentDetails" : [ { "TheoryMarks" : 78, "PracticalMarks" : 91 }, { "TheoryMarks" : 75, "PracticalMarks" : 75 } ] } { "_id" : ObjectId("5c8edaf12f684a30fbdfd587"), "StudentId" : 102, "StudentDetails" : [ { "TheoryMarks" : 91, "PracticalMarks" : 91 }, { "TheoryMarks" : 75, "PracticalMarks" : 75 } ] }
这是查找具有数组的文档的查询,该数组不包含MongoDB中具有特定字段值的文档-
> db.documentWithAParticularFieldValueDemo.find({'StudentDetails.TheoryMarks': {$nin: [78]}}).pretty();
以下是输出-
{ "_id" : ObjectId("5c8edaf12f684a30fbdfd587"), "StudentId" : 102, "StudentDetails" : [ { "TheoryMarks" : 91, "PracticalMarks" : 91 }, { "TheoryMarks" : 75, "PracticalMarks" : 75 } ] }