MongoDB find in

MongoDB find in command | Complete tutorial in 2022

MongoDB is one of the most popular No SQL databases which can handle a high volume of data. In this blog, we will learn in detail about MongoDB find in. So let’s get started.

MongoDB in query

The $in operator in MongoDB is used to search the document where the value of a field equals any value in the specified filter array.

In case if you are new to MongoDB, you can follow this tutorial to get a basic idea about mongodb commands.

The syntax of $in operator follows the below pattern

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

where thefield is the field you want to search in the mongo document.

<value1>, <value2>..<valueN> is the list of fields to be matched.

MongoDB find in example

To explain how the find $in operator work in MongoDB, we will be using the below data

[
  {
    "title": "The Last Student Returns",
    "meta": { "rating": 9.5, "aired": 2018 },
    "visitors": 400,
    "expectedVisitors": 300,
    "genre": ["thriller", "drama", "action"]
  },
  {
      "title": "Supercharged Teaching",
      "meta": {"rating": 9.3, "aired": 2016 },
      "visitors": 700,
      "expectedVisitors": 300,
      "genre": ["thriller", "action"]
  },
  {
      "title": "Teach me if you can",
      "meta": {"rating": 8.5, "aired": 2014 },
      "visitors": 200,
      "expectedVisitors": 250,
      "genre": ["action", "thriller"]
  },
  {
      "title": "terminator",
      "meta": {"rating": 8.5, "aired": 2014 },
      "visitors": 300,
      "expectedVisitors": 200,
      "genre": ["action", "scify"]
  }
]

Let’s insert the above data into the MongoDB movie collection

> db.movie.insertMany([
...   {
...     "title": "The Last Student Returns",
...     "meta": { "rating": 9.5, "aired": 2018 },
...     "visitors": 400,
...     "expectedVisitors": 300,
...     "genre": ["thriller", "drama", "action"]
...   },
...   {
...       "title": "Supercharged Teaching",
...       "meta": {"rating": 9.3, "aired": 2016 },
...       "visitors": 700,
...       "expectedVisitors": 300,
...       "genre": ["thriller", "action"]
...   },
...   {
...       "title": "Teach me if you can",
...       "meta": {"rating": 8.5, "aired": 2014 },
...       "visitors": 200,
...       "expectedVisitors": 250,
...       "genre": ["action", "thriller"]
...   },
...   {
...       "title": "terminator",
...       "meta": {"rating": 8.5, "aired": 2014 },
...       "visitors": 300,
...       "expectedVisitors": 200,
...       "genre": ["action", "scify"]
...   }
... ])
{
	"acknowledged" : true,
	"insertedIds" : [
		ObjectId("61018c185cddf7c92e7e9130"),
		ObjectId("61018c185cddf7c92e7e9131"),
		ObjectId("61018c185cddf7c92e7e9132"),
		ObjectId("61018c185cddf7c92e7e9133")
	]
}

Verify if the data gets properly inserted

> db.movie.find().pretty()
{
	"_id" : ObjectId("61018c185cddf7c92e7e9130"),
	"title" : "The Last Student Returns",
	"meta" : {
		"rating" : 9.5,
		"aired" : 2018
	},
	"visitors" : 400,
	"expectedVisitors" : 300,
	"genre" : [
		"thriller",
		"drama",
		"action"
	]
}
{
	"_id" : ObjectId("61018c185cddf7c92e7e9131"),
	"title" : "Supercharged Teaching",
	"meta" : {
		"rating" : 9.3,
		"aired" : 2016
	},
	"visitors" : 700,
	"expectedVisitors" : 300,
	"genre" : [
		"thriller",
		"action"
	]
}
{
	"_id" : ObjectId("61018c185cddf7c92e7e9132"),
	"title" : "Teach me if you can",
	"meta" : {
		"rating" : 8.5,
		"aired" : 2014
	},
	"visitors" : 200,
	"expectedVisitors" : 250,
	"genre" : [
		"action",
		"thriller"
	]
}
{
	"_id" : ObjectId("61018c185cddf7c92e7e9133"),
	"title" : "terminator",
	"meta" : {
		"rating" : 8.5,
		"aired" : 2014
	},
	"visitors" : 300,
	"expectedVisitors" : 200,
	"genre" : [
		"action",
		"scify"
	]
}

Mongodb find in to match values

Let’s try to find documents where visitors are either 200 or 300

Type the below command to fetch the required data

db.movie.find({"visitors": {$in: [300,200]}}).pretty()
> db.movie.find({"visitors": {$in: [300,200]}}).pretty()
{
	"_id" : ObjectId("61018c185cddf7c92e7e9132"),
	"title" : "Teach me if you can",
	"meta" : {
		"rating" : 8.5,
		"aired" : 2014
	},
	"visitors" : 200,
	"expectedVisitors" : 250,
	"genre" : [
		"action",
		"thriller"
	]
}
{
	"_id" : ObjectId("61018c185cddf7c92e7e9133"),
	"title" : "terminator",
	"meta" : {
		"rating" : 8.5,
		"aired" : 2014
	},
	"visitors" : 300,
	"expectedVisitors" : 200,
	"genre" : [
		"action",
		"scify"
	]
}
>

MongoDB find in array of strings

Let’s try to find documents where the genre is either“scify” or “drama”]

db.movie.find({"genre": {$in: ["scify", "drama"]}}).pretty()

> db.movie.find({"genre": {$in: ["scify", "drama"]}}).pretty()
{
	"_id" : ObjectId("61018c185cddf7c92e7e9130"),
	"title" : "The Last Student Returns",
	"meta" : {
		"rating" : 9.5,
		"aired" : 2018
	},
	"visitors" : 400,
	"expectedVisitors" : 300,
	"genre" : [
		"thriller",
		"drama",
		"action"
	]
}
{
	"_id" : ObjectId("61018c185cddf7c92e7e9133"),
	"title" : "terminator",
	"meta" : {
		"rating" : 8.5,
		"aired" : 2014
	},
	"visitors" : 300,
	"expectedVisitors" : 200,
	"genre" : [
		"action",
		"scify"
	]
}
>

Let’s take another example and find the document where the title contains either student or Teach.

db.movie.find({"title": {$in : [/Student/,/Teach/]}}).pretty()
> db.movie.find({"title": {$in : [/Student/,/Teach/]}}).pretty()
{
	"_id" : ObjectId("61018c185cddf7c92e7e9130"),
	"title" : "The Last Student Returns",
	"meta" : {
		"rating" : 9.5,
		"aired" : 2018
	},
	"visitors" : 400,
	"expectedVisitors" : 300,
	"genre" : [
		"thriller",
		"drama",
		"action"
	]
}
{
	"_id" : ObjectId("61018c185cddf7c92e7e9131"),
	"title" : "Supercharged Teaching",
	"meta" : {
		"rating" : 9.3,
		"aired" : 2016
	},
	"visitors" : 700,
	"expectedVisitors" : 300,
	"genre" : [
		"thriller",
		"action"
	]
}
{
	"_id" : ObjectId("61018c185cddf7c92e7e9132"),
	"title" : "Teach me if you can",
	"meta" : {
		"rating" : 8.5,
		"aired" : 2014
	},
	"visitors" : 200,
	"expectedVisitors" : 250,
	"genre" : [
		"action",
		"thriller"
	]
}

MongoDB find in array of objects

In this session, we will understand how to use MongoDB to find data from an array of strings. Suppose we have the below awards data.

[
  {
    name: "Naive",
    contribs: ['Fortran', 'ALGOL'],
    awards: [
        {
            award: 'National Medal',
            year: 1975,
        },
        {
            award: 'Turing Award',
            year: 1977,
        }
      ]
    },
   {
    name: "Peter",
    contribs: ['Backus-Naur Form', 'FP'],
    awards: [
        {
            award: 'Global Medal',
            year: 1988,
        },
        {
            award: 'Hippa Award',
            year: 2020,
        }
      ]
    },
  {
    name: "Jack",
    contribs: ['GDPR', 'LOKS'],
    awards: [
        {
            award: 'National Medal',
            year: 1988,
        },
        {
            award: 'Hippa Award',
            year: 2019,
        }
      ]
    }
]

We want to find the name of who won the ‘National Medal’ award in 1975. From the above data, it is clear that the two names won theNational Medal award.

To search for a user who won the‘National Medal’ award in 1975, we need to use the below query

db.award.find({awards: {$elemMatch: {"award":"National Medal" , "year":1975}}})
db.award.find({awards: {$elemMatch: {"award":"National Medal" , "year":1975}}}).pretty()
{
	"_id" : ObjectId("61bc972a3d14cea591b54f98"),
	"name" : "Naive",
	"contribs" : [
		"Fortran",
		"ALGOL"
	],
	"awards" : [
		{
			"award" : "National Medal",
			"year" : 1975
		},
		{
			"award" : "Turing Award",
			"year" : 1977
		}
	]
}

we need to use $elemMatch which allows the user to match one or more components within the same array.

MongoDB find multiple condition

In this session, we will understand how to use multiple conditions in mongodb. We will be using movie data for the demo.

Suppose we want to filter out movies with either action or drama genres and have visitors of 400 or 700.

db.movie.find({"visitors": {$in: [400,700]}, "genre": {$in: ["action","drama"]}}).pretty()
db.movie.find({"visitors": {$in: [400,700]}, "genre": {$in: ["action","drama"]}}).pretty()
{
	"_id" : ObjectId("61bc90b73d14cea591b54f8f"),
	"title" : "The Last Student Returns",
	"meta" : {
		"rating" : 9.5,
		"aired" : 2018
	},
	"visitors" : 400,
	"expectedVisitors" : 300,
	"genre" : [
		"thriller",
		"drama",
		"action"
	]
}
{
	"_id" : ObjectId("61bc90b73d14cea591b54f90"),
	"title" : "Supercharged Teaching",
	"meta" : {
		"rating" : 9.3,
		"aired" : 2016
	},
	"visitors" : 700,
	"expectedVisitors" : 300,
	"genre" : [
		"thriller",
		"action"
	]
}

MongoDB find specific field

So far, we have used fetched the entire document from MongoDB based on various find conditions. This session, we will understand how to fetch only a particular field from the mongo collection.

In MongoDB, we can fetch specific fields by specifying {<field>:1} while finding the data. Let’s write a query to display only the title field from the movie document.

db.movie.find({},{"title":1})
 db.movie.find({},{"title":1})
{ "_id" : ObjectId("61cde33b5ac17e32a0d6e36a"), "title" : "The Last Student Returns" }
{ "_id" : ObjectId("61cde33b5ac17e32a0d6e36b"), "title" : "Supercharged Teaching" }
{ "_id" : ObjectId("61cde33b5ac17e32a0d6e36c"), "title" : "Teach me if you can" }
{ "_id" : ObjectId("61cde33b5ac17e32a0d6e36d"), "title" : "terminator" }

By default, the id field will be fetched along with all the fields we mentioned as 1. If you do not want the id field to be displayed, you can pass _id:0.

 db.movie.find({},{"title":1, "_id":0})
 db.movie.find({},{"title":1, "_id":0})
{ "title" : "The Last Student Returns" }
{ "title" : "Supercharged Teaching" }
{ "title" : "Teach me if you can" }
{ "title" : "terminator" }

You can also fetch more than one field by mentioning the field name as comma separated value. Type the below command to fetch the title and genre field

db.movie.find({},{"title":1,"genre":1 ,"_id":0})
db.movie.find({},{"title":1,"genre":1 ,"_id":0})
{ "title" : "The Last Student Returns", "genre" : [ "thriller", "drama", "action" ] }
{ "title" : "Supercharged Teaching", "genre" : [ "thriller", "action" ] }
{ "title" : "Teach me if you can", "genre" : [ "action", "thriller" ] }
{ "title" : "terminator", "genre" : [ "action", "scify" ] }

Conclusion

I hope you like this tutorial about using MongoDB to find in command filter out documents. We have also seen the usage of find in command by simple movie data. Please let me know if you face any issues while using the find in command.

More To read?

MongoDB commands you should be aware of

MongoDB with python | pymongo

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top