MongoDB: $nin and $in not working together in $elemMatch to fetch documents having subjects “MongoDB”, but not “Java”

MongoDBDatabaseBig Data Analytics

For such kind of fetching, use only $nin and $in. Let us create a collection with documents −

> 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")
}

Display all documents from a collection with the help of find() method −

> db.demo140.find();

This will produce the following output −

{ "_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++" ] }

Here is the query to fetch documents having subjects “MongoDB” but not “Java” −

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

This will produce the following output −

[
   {
      "_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"
      ]
   }
]
raja
Published on 31-Mar-2020 16:04:12
Advertisements