Set regex in MongoDB $in?

MongoDBDatabaseBig Data Analytics

Let us create a collection with documents −

> db.demo675.insertOne({
... "ListOfNames":["John","Chris","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f5b404263e90dac943ef")
}
> db.demo675.insertOne({ "ListOfNames":["Bob","Johnson","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f5c804263e90dac943f0")
}
> db.demo675.insertOne({ "ListOfNames":["Jace","Sam"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea3f5d304263e90dac943f1")
}

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

> db.demo675.find();

This will produce the following output −

{ "_id" : ObjectId("5ea3f5b404263e90dac943ef"), "ListOfNames" : [ "John", "Chris", "David" ] }
{ "_id" : ObjectId("5ea3f5c804263e90dac943f0"), "ListOfNames" : [ "Bob", "Johnson", "Sam" ] }
{ "_id" : ObjectId("5ea3f5d304263e90dac943f1"), "ListOfNames" : [ "Jace", "Sam" ] }

Following is the query to query with regexp and array −

> db.demo675.find({"ListOfNames": {$in:[/John/,/J/]}});

This will produce the following output −

{ "_id" : ObjectId("5ea3f5b404263e90dac943ef"), "ListOfNames" : [ "John", "Chris", "David" ] }
{ "_id" : ObjectId("5ea3f5c804263e90dac943f0"), "ListOfNames" : [ "Bob", "Johnson", "Sam" ] }
{ "_id" : ObjectId("5ea3f5d304263e90dac943f1"), "ListOfNames" : [ "Jace", "Sam" ] }
raja
Published on 13-May-2020 10:03:34
Advertisements