MongoDB:$ nin和$ in不能在$ elemMatch中一起工作以获取主题为“ MongoDB”而不是“ Java”的文档

对于此类获取,仅使用$nin和$in。让我们创建一个包含文档的集合-

> db.demo140.insertOne({"Id":101,"Subjects":["MongoDB","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c149fdf09dd6d08539a9")
}
> db.demo140.insertOne({"Id":102,"Subjects":["MongoDB","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c14cfdf09dd6d08539aa")
}
> db.demo140.insertOne({"Id":103,"Subjects":["MongoDB","PL/SQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c157fdf09dd6d08539ab")
}
> db.demo140.insertOne({"Id":104,"Subjects":["MongoDB","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c163fdf09dd6d08539ac")
}
> db.demo140.insertOne({"Id":105,"Subjects":["C","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e31c16ffdf09dd6d08539ad")
}

find()方法的帮助下显示集合中的所有文档-

> db.demo140.find();

这将产生以下输出-

{ "_id" : ObjectId("5e31c149fdf09dd6d08539a9"), "Id" : 101, "Subjects" : [ "MongoDB", "MySQL" ] }
{ "_id" : ObjectId("5e31c14cfdf09dd6d08539aa"), "Id" : 102, "Subjects" : [ "MongoDB", "Java" ] }
{ "_id" : ObjectId("5e31c157fdf09dd6d08539ab"), "Id" : 103, "Subjects" : [ "MongoDB", "PL/SQL" ] }
{ "_id" : ObjectId("5e31c163fdf09dd6d08539ac"), "Id" : 104, "Subjects" : [ "MongoDB", "SQL Server" ] }
{ "_id" : ObjectId("5e31c16ffdf09dd6d08539ad"), "Id" : 105, "Subjects" : [ "C", "C++" ] }

这是获取主题为“ MongoDB”但主题为“ Java”的文档的查询-

> db.demo140.find({$and:[{Subjects:{$in:['MongoDB']}}, {Subjects:{$nin:['Java']}}]}).toArray();

这将产生以下输出-

[
   {
      "_id" : ObjectId("5e31c149fdf09dd6d08539a9"),
      "Id" : 101,
      "Subjects" : [
         "MongoDB",
         "MySQL"
      ]
   },
   {
      "_id" : ObjectId("5e31c157fdf09dd6d08539ab"),
      "Id" : 103,
      "Subjects" : [
         "MongoDB",
         "PL/SQL"
      ]
   },
   {
      "_id" : ObjectId("5e31c163fdf09dd6d08539ac"),
      "Id" : 104,
      "Subjects" : [
         "MongoDB",
         "SQL Server"
      ]
   }
]