我们可以在 MongoDB 中同时使用 NOT 和 AND 吗?
mongodbdatabasebig data analytics更新于 2026/1/16 18:37:17
是的,我们可以在 MongoDB 中同时使用 NOT 和 AND。语法如下
NOT X AND NOT Y = NOT (X AND Y) 让我们看看上述语法的工作原理。 如果 X 和 Y 同时为真,则最终结果为假。 如果其中一个操作数的结果为假,则最终结果为真。
以下是创建包含文档的集合的查询
> db.NotAndDemo.insertOne({"StudentName":"John","StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c98746a330fd0aa0d2fe4a8")
}
> db.NotAndDemo.insertOne({"StudentName":"John","StudentCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c987478330fd0aa0d2fe4a9")
}
> db.NotAndDemo.insertOne({"StudentName":"David","StudentCountryName":"AUS"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c987487330fd0aa0d2fe4aa")
}
> db.NotAndDemo.insertOne({"StudentName":"Chris","StudentCountryName":"UK"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9874ac330fd0aa0d2fe4ab")
}
> db.NotAndDemo.insertOne({"StudentName":"Chris","StudentCountryName":"US"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9874b7330fd0aa0d2fe4ac")
}
以下是借助 find() 方法显示集合中的所有文档的查询
> db.NotAndDemo.find().pretty();
This will produce the following output:
{
"_id" : ObjectId("5c98746a330fd0aa0d2fe4a8"),
"StudentName" : "John",
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c987478330fd0aa0d2fe4a9"),
"StudentName" : "John",
"StudentCountryName" : "UK"
}
{
"_id" : ObjectId("5c987487330fd0aa0d2fe4aa"),
"StudentName" : "David",
"StudentCountryName" : "AUS"
}
{
"_id" : ObjectId("5c9874ac330fd0aa0d2fe4ab"),
"StudentName" : "Chris",
"StudentCountryName" : "UK"
}
{
"_id" : ObjectId("5c9874b7330fd0aa0d2fe4ac"),
"StudentName" : "Chris",
"StudentCountryName" : "US"
}
以下是同时使用 NOT 和 AND 的查询,与 NOT (X AND Y) 的 NOT X OR NOT Y 相同
> db.NotAndDemo.find({
... "$or": [
... {"StudentName": {"$ne": "Chris"}},
... {"StudentCountryName": {"$ne": "US"}}
... ]
... }).pretty();
这将产生以下输出 −
{
"_id" : ObjectId("5c98746a330fd0aa0d2fe4a8"),
"StudentName" : "John",
"StudentCountryName" : "US"
}
{
"_id" : ObjectId("5c987478330fd0aa0d2fe4a9"),
"StudentName" : "John",
"StudentCountryName" : "UK"
}
{
"_id" : ObjectId("5c987487330fd0aa0d2fe4aa"),
"StudentName" : "David",
"StudentCountryName" : "AUS"
}
{
"_id" : ObjectId("5c9874ac330fd0aa0d2fe4ab"),
"StudentName" : "Chris",
"StudentCountryName" : "UK"
}

