Find document in MongoDB where at least one item from an array is not in the other?


For this, set regex in MongoDB find(). Let us create a collection with documents −

> db.demo228.insertOne({"Subjects":["MongoDB","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fa51f03d395bdc213473b")
}
> db.demo228.insertOne({"Subjects":["MongoDB","Java","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3fa52c03d395bdc213473c")
}

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

> db.demo228.find();

This will produce the following output −

{ "_id" : ObjectId("5e3fa51f03d395bdc213473b"), "Subjects" : [ "MongoDB", "Java" ] }
{ "_id" : ObjectId("5e3fa52c03d395bdc213473c"), "Subjects" : [ "MongoDB", "Java", "MySQL" ] }

Following is the query to find documents where at least one item from an array is not in the other −

> db.demo228.find({ "Subjects": /^(?!MongoDB|Java)/ });

This will produce the following output −

{ "_id" : ObjectId("5e3fa52c03d395bdc213473c"), "Subjects" : [ "MongoDB", "Java", "MySQL" ] }

Updated on: 30-Mar-2020

103 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements