Search multiple fields for multiple values in MongoDB?

MongoDBDatabaseBig Data Analytics

To search multiple fields for multiple values in MongoDB, you can use $text and $search operator. Let us first create a collection with documents

>db.searchMultipleFieldsDemo.insertOne({"_id":100,"FirstSubject":"Java","SecondSubject":"MongoDB"});
{ "acknowledged" : true, "insertedId" : 100 }
>db.searchMultipleFieldsDemo.insertOne({"_id":101,"FirstSubject":"MongoDB","SecondSubject":"MySQL"});
{ "acknowledged" : true, "insertedId" : 101 }
>db.searchMultipleFieldsDemo.insertOne({"_id":102,"FirstSubject":"MySQL","SecondSubject":"Java"});
{ "acknowledged" : true, "insertedId" : 102 }

Following is the query to display all documents from a collection with the help of find() method

> db.searchMultipleFieldsDemo.find().pretty();

This will produce the following output

{ "_id" : 100, "FirstSubject" : "Java", "SecondSubject" : "MongoDB" }
{ "_id" : 101, "FirstSubject" : "MongoDB", "SecondSubject" : "MySQL" }
{ "_id" : 102, "FirstSubject" : "MySQL", "SecondSubject" : "Java" }

Following is the query to search multiple fields for multiple values in MongoDB

> db.searchMultipleFieldsDemo.find({"$text":{"$search":"Java MongoDB"}});

This will produce the following output

{ "_id" : 102, "FirstSubject" : "MySQL", "SecondSubject" : "Java" }
{ "_id" : 100, "FirstSubject" : "Java", "SecondSubject" : "MongoDB" }
{ "_id" : 101, "FirstSubject" : "MongoDB", "SecondSubject" : "MySQL" }
raja
Published on 11-Apr-2019 10:55:02
Advertisements