获取所有 MongoDB 文档,但不要符合两个给定条件的文档。
按照以下给定的场景,获取所有符合某些给定条件的 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"
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP