在以下任何一种情况下,获取具有某些给定条件的所有MongoDB文档
情况1以下是使用$ne运算符查询没有单个条件的所有文档的查询
db.yourCollectionName.find({yourFieldName:{$ne:"yourValue"}}).pretty();
情况2以下是使用$nin运算符查询所有没有两个给定条件的文档的查询
db.yourCollectionName.find({yourFieldName:{$nin:["yourValue1","yourValue2"]}}).pretty();
让我们首先创建一个集合。以下是使用文档创建集合的查询
>db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Larry","StudentSubjectName":"Java"}); { "acknowledged" : true, "insertedId" : ObjectId("5c993d82330fd0aa0d2fe4d2") } >db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Chris","StudentSubjectName":"C++"}); { "acknowledged" : true, "insertedId" : ObjectId("5c993d8f330fd0aa0d2fe4d3") } >db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"Robert","StudentSubjectName":"C"}); { "acknowledged" : true, "insertedId" : ObjectId("5c993d99330fd0aa0d2fe4d4") } >db.findAllExceptFromOneOrtwoDemo.insertOne({"StudentName":"David","StudentSubjectName":"Python"}); { "acknowledged" : true, "insertedId" : ObjectId("5c993da4330fd0aa0d2fe4d5") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.findAllExceptFromOneOrtwoDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5c993d82330fd0aa0d2fe4d2"), "StudentName" : "Larry", "StudentSubjectName" : "Java" } { "_id" : ObjectId("5c993d8f330fd0aa0d2fe4d3"), "StudentName" : "Chris", "StudentSubjectName" : "C++" } { "_id" : ObjectId("5c993d99330fd0aa0d2fe4d4"), "StudentName" : "Robert", "StudentSubjectName" : "C" } { "_id" : ObjectId("5c993da4330fd0aa0d2fe4d5"), "StudentName" : "David", "StudentSubjectName" : "Python" }
案例1单一条件
以下是查询
> db.findAllExceptFromOneOrtwoDemo.find({StudentSubjectName:{$ne:"C"}}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c993d82330fd0aa0d2fe4d2"), "StudentName" : "Larry", "StudentSubjectName" : "Java" } { "_id" : ObjectId("5c993d8f330fd0aa0d2fe4d3"), "StudentName" : "Chris", "StudentSubjectName" : "C++" } { "_id" : ObjectId("5c993da4330fd0aa0d2fe4d5"), "StudentName" : "David", "StudentSubjectName" : "Python" }
案例2两个条件
以下是查询
>db.findAllExceptFromOneOrtwoDemo.find({StudentSubjectName:{$nin:["C++","Python"]}}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5c993d82330fd0aa0d2fe4d2"), "StudentName" : "Larry", "StudentSubjectName" : "Java" } { "_id" : ObjectId("5c993d99330fd0aa0d2fe4d4"), "StudentName" : "Robert", "StudentSubjectName" : "C" }